algorithm - 要求解决八皇后难题的算法

标签 algorithm recursion puzzle chess

<分区>

Possible Duplicate:
Dumb 8 Queens problem in C++

嗨 这个问题我过来了 **

write an algorithm to print all ways of arranging 8 kings on the chess board so that none have same row,column ,diagonal

**

//initialize chess[i][j] to 0;
int king=100; //any other number except 0/1

for(i=0;i<8;i++)
{
for(j=0;j<8;j++)
{
//select any one position for the first column... lets start with j=0,i=0
if(chess[i][j]!=1)
chess[i][j]=king;
//now we should cross all rows with value i and column with value j
chess[i][]=1; 
print(when chess[][]=king)
// we cannot enter king if chess[][]=1

}
}

如何检查对角线部分?还有如何枚举所有可能的情况?

提前致谢

最佳答案

回答具体问题:

棋盘上的对角线走法总是从 (m,n) 到 (m+/-k, n+/-k);也就是说,您水平移动的空间与垂直移动的空间一样多。因此,要检查两个皇后,一个在 (i,j) 上,一个在 (p,q) 上,是否在对角线上互相攻击,您需要检查是否 abs(i-p) == abs(j-q)

要划掉 (p,q) 上所有可以被皇后对角线攻击的方格,需要四个循环形式

for (i = p, j = q; i >= 0, j >= 0; i--, j--) { board[i][j] = 1 }

for (i = p, j = q; i >= 0, j < 8; i--, j++)  { board[i][j] = 1 }

for (i = p, j = q; i < 8, j < 8; i++, j++)   { board[i][j] = 1 }

for (i = p, j = q; i < 8, j >= 0; i++, j--)  { board[i][j] = 1 }

也就是说,您以皇后为中心走 x 的所有四个臂,划掉方 block ,直到碰到棋盘的边缘。

关于algorithm - 要求解决八皇后难题的算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5486945/

相关文章:

python - 在 8 拼图游戏中用 Python 计算曼哈顿距离

c - 无法使用 C 为无向图创建邻接表

algorithm - 通知网络所有节点的最短时间

c - 拼写检查算法

java - 递归java星号

java - 查找字符串中大写字母出现次数的递归方法 - 使用辅助方法

algorithm - 如果某些边缘是固定的,那么用于 MST 的标准 Kruskal 类方法是否可行?

java - 递归检查

data-structures - 项目欧拉问题 67 : find maximum cost path in 100-row triangle

java - 数独类谜题的笼式约束