在棋盤上放置8個皇后,使得它們互不攻擊,此時每個皇后的攻擊範圍為同行同列和同對角線,要求找出所有解,乙個很簡單的排列組合問題,每行每列每斜列只能有乙個皇后
/**
* created by max on 17-5-14.
*/public
class
eightqueen
public
static
void
location(int column)
for (int i = 0;i<8 ;i++)
if (i==7)
map[7][column] = 0;
row[i] = 0;}}
public
static
boolean
attack(int x,int y)
i++;
}i = 0;
while(x-i>=0&&y-i>=0)
i++;
}i = 0;
while (x-i>=0&&y+i<8)
i++;
}i = 0;
while (x+i<8&&y-i>=0)
i++;
}i = 0;
while(i<8)
i++;
}map[x][y] = 1;
return
true;
}}
優化後
/**
* created by max on 17-5-14.
*/public
class
eightqueenbetter
static
void search(int row_number)
for (int i =0 ;i<8;i++)
}if (ok)
search(row_number+1);}}
}
在優化
private static byte accupied = new byte[3][15];
static void search2(int column)
for (int i = 0;i<8;i++)
}}
八皇后問題
八皇后問題 ackarlix 八皇后問題是乙個古老而著名的問題,是回溯演算法的典型例題。該問題是十九世紀著名的數學家高斯 1850 年提出 在 8x8格的西洋棋上擺放八個皇后,使其不能互相攻擊,即任意兩個皇后都不能處於同一行 同一列或同一斜線上,問有多少種擺法。高斯認為有 76種方案。1854 年在...
八皇后問題
include iostream.h int a 8 8 棋盤 int r 8 結果 int i,j int count 0 void init i j 0 int judge int x,int y for int mi x 1,mj y mi 1 mi for int ri x 1,rj y 1...
八皇后問題
package quess 由於八個皇后的任意兩個不能處在同一行,那麼這肯定是每乙個皇后佔據一行。於是我們可以定義乙個陣列columnindex 8 陣列中第i個數字表示位於第i行的皇后的列號。先把columnindex的八個數字分別用0 7初始化,接下來我們要做的事情就是對陣列columninde...