8皇后功能问题 - placequeen函数不执行(回溯)
一切正常,但是我的最后一个功能无法正常执行。 ''' //安全检查
bool Board::isSafe(int row, int col) {
for (int i = 0; i < col ; i++)
if (myBoard[row][i]==1)
return false;
for (int i=row, j=col; i>=0 && j>=0; i--, j--)
if (myBoard[i][j]==1)
return false;
for (int i=row, j=col; j>=0 && i<8; i++, j--)
if (myBoard[i][j]==1)
return false;
return true;
};
//放置皇后 - &gt;此功能在主机上正常工作
bool Board::placeQueen(int row, int col){
if (col >= 8)
{
return true;
}
else {
for (int i = 0; i < 8; i++) {
myBoard[i][col] = 1;
if (isSafe(i,col)==true) {
Board::placeQueen(row, col + 1);
}
myBoard[i][col] = 0;
}
}
return false;
};
,我执行此myboard.placequeen(0,0);
,但板上的所有内容都是零。
everything works fine but my last function doesn't execute properly.
'''
//Safe check
bool Board::isSafe(int row, int col) {
for (int i = 0; i < col ; i++)
if (myBoard[row][i]==1)
return false;
for (int i=row, j=col; i>=0 && j>=0; i--, j--)
if (myBoard[i][j]==1)
return false;
for (int i=row, j=col; j>=0 && i<8; i++, j--)
if (myBoard[i][j]==1)
return false;
return true;
};
//Placing the Queens -> This function done work properly
bool Board::placeQueen(int row, int col){
if (col >= 8)
{
return true;
}
else {
for (int i = 0; i < 8; i++) {
myBoard[i][col] = 1;
if (isSafe(i,col)==true) {
Board::placeQueen(row, col + 1);
}
myBoard[i][col] = 0;
}
}
return false;
};
in the main, I do this myBoard.placeQueen(0,0);
but everything on the board is Zero.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
第一期。您的
ISSAFE
功能正在同一行和对角线上扫描皇后区,但没有在同一列上检查皇后区。对角检查看起来可疑。它正在向上/向左/向左扫描,但并没有向上/右/向右扫描。第二期。当
col == 8
时,您的placequeen
函数正在停止其递归,当板上放置8个皇后时,不一定。使用另一个变量跟踪板上有多少皇后。它可以是全球或通过递归通过的。第三期。您的
placequeen
函数仅递增列变量,但切勿递增行变量。我认为它从未超过第0行。这些可能不是您唯一的错误。
如果您展示更多进展,我将提供更多提示。
First issue. Your
IsSafe
function is scanning for queens on the same row and diagonals, but isn't checking for queens on the same column. And the diagonal checking looks suspicious. It's scanning up/left and down/left, but it's not scanning up/right and down/right.Second issue. Your
placeQueen
function is halting its recursion whencol == 8
, not necessarily when there are 8 queens placed on the board. Use another variable to keep track of how many queens are on the board. It can be a global or passed via recursion.Third issue. Your
placeQueen
function is only incrementing the column variable, but never increments the row variable. I don't think it ever gets past row 0.Those may not be your only bugs.
I'll provide more hints if you demonstrate more progress.