求算法来解决八皇后难题

发布于 2024-10-29 06:51:57 字数 755 浏览 0 评论 0原文

可能的重复:
C++ 中的愚蠢 8 皇后问题

嗨 我走过来了这个问题 **

编写一个算法来打印所有方式 在国际象棋上排列 8 个国王 板,以便没有相同的 行、列、对角线

**

//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

}
}

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

感谢在广告..

Possible Duplicate:
Dumb 8 Queens problem in C++

Hi
I came over this question
**

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

}
}

how to check the diagonal part as well? also how to enumerate all the possible cases?

Thanks in adv..

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

荆棘i 2024-11-05 06:51:57

回答具体问题:

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

要划掉 (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 的所有四个臂,划掉方格,直到击中板的边缘。

To answer the specific question:

A diagonal move on the chessboard is always from (m,n) to (m+/-k, n+/-k); i.e. you move as many spaces horizontally as you do vertically. Therefore, to check if two queens, one on (i,j) and one on (p,q) are diagonally attacking each other, you check if abs(i-p) == abs(j-q).

To cross out all squares that can be diagonally attacked by a queen on (p,q), you need four loops of the form

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 }

that is, you walk all four arms of the x centred on your queen, crossing out squares till you hit the edge of the board.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文