問(wèn)題描述:
在8x8的網(wǎng)格上分扎,放置皇后兩個(gè)皇后阅茶,兩個(gè)皇后之間不能在同一行,也不能在同一列术荤,也不能在對(duì)角線(xiàn)上。
class Program
? ? {
? ? ? ? static int N = 8;
? ? ? ? static int[] index = new int[N];
? ? ? ? static int solution = 0;
? ? ? ? static void Main(string[] args)
? ? ? ? {
? ? ? ? ? ? for (int i = 0; i < N; i++)
? ? ? ? ? ? ? ? index[i] = 0;
? ? ? ? ? ? //Test8Huanghou();
? ? ? ? ? ? //Test8Huanghou2();
? ? ? ? ? ? //默認(rèn)列索引0開(kāi)始
? ? ? ? ? ? Test8Huanghou3(0);
? ? ? ? ? ? Console.ReadLine();
? ? ? ? }
? ? ? ? //參數(shù)為列的索引然低,從0開(kāi)始
? ? ? ? private static void Test8Huanghou3(int col)
? ? ? ? {
? ? ? ? ? ? //選定一列后喜每,循環(huán)這一列的每一行
? ? ? ? ? ? for( int i = 0;i < N;i++)
? ? ? ? ? ? {
? ? ? ? ? ? ? ? if( col == N)
? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? if( solution > 2)
? ? ? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? ? ? return;
? ? ? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? ? ? solution++;
? ? ? ? ? ? ? ? ? ? Console.WriteLine("-solution:" + solution);
? ? ? ? ? ? ? ? ? ? PrintMap();
? ? ? ? ? ? ? ? ? ? return;
? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? //假定將一個(gè)皇后放到col列的i行
? ? ? ? ? ? ? ? index[col] = i;//注意此處,數(shù)組的索引是列索引雳攘,數(shù)組索引對(duì)應(yīng)值是這一列的第幾行放置了皇后(同時(shí)注意索引從0開(kāi)始)
? ? ? ? ? ? ? ? //檢測(cè)當(dāng)前放置的是否可以放
? ? ? ? ? ? ? ? if(CheckCanSet(col))
? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? //如果可以放置带兜,則開(kāi)始進(jìn)行下一列的放置
? ? ? ? ? ? ? ? ? ? Test8Huanghou3(col + 1);
? ? ? ? ? ? ? ? }
? ? ? ? ? ? }
? ? ? ? }
? ? ? ? //檢測(cè)某個(gè)位置是否可放置
? ? ? ? private static bool CheckCanSet(int col)
? ? ? ? {
? ? ? ? ? ? //根據(jù)傳遞進(jìn)來(lái)的列,我們從左往右進(jìn)行檢測(cè)吨灭,從0到(col-1)依次檢測(cè)
? ? ? ? ? ? for( int i = 0;i < col;i++)
? ? ? ? ? ? {
? ? ? ? ? ? ? ? //如果是同一行刚照,返回false
? ? ? ? ? ? ? ? if( index[i] == index[col])
? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? return false;
? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? //是否存在斜線(xiàn)上的元素,返回false,這里用到了斜率
? ? ? ? ? ? ? ? if( Math.Abs(index[col] - index[i]) == Math.Abs(col - i))
? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? return false;
? ? ? ? ? ? ? ? }
? ? ? ? ? ? }
? ? ? ? ? ? return true;
? ? ? ? }
? ? ? ? private static void PrintMap()
? ? ? ? {
? ? ? ? ? ? for( int i = 0;i< N;i++)
? ? ? ? ? ? {
? ? ? ? ? ? ? ? //+1輸出是為了看著清晰
? ? ? ? ? ? ? ? Console.Write("(" + (i+1) + "," + (index[i] + 1) + ")");
? ? ? ? ? ? ? ? Console.WriteLine("=====");
? ? ? ? ? ? }
? ? ? ? }
}