我正在尝试在python中实现N- Queens问题。我需要一个小帮助来设计算法来检查是否给定皇后的位置检查棋盘上是否有其他女王在对角线上。
我试图设计一个函数diagonal_check(board, row, col)
,其中板是N*N数组矩阵,其中'1'代表女王的存在,'0'代表缺席。我将传递数组和皇后的位置(row,col)给函数。如果在它的对角线上存在任何其他皇后,我的函数必须返回false,否则返回true。
如果有人可以帮助我的算法diagonal_check
函数。不查找任何特定的语言代码
设左上角为(0,0)
正方形(row,col)的对角线方向为col-row+7
正方形(row,col)的对角线方向为row+col
简单地检查两个皇后是否有相同的col-row+7
或row+col
应该告诉你两个皇后是否在相同的对角线上。如果你仍然有点困惑,可以在谷歌上搜索一个棋盘图像。
boolean diagonalCheck(board, row, col) {
int tempRow ;
int tempCol ;
//algorithm to check left diagonal
if (row >= col) {
tempRow = row-col;
tempCol = 0;
} else {
tempRow = 0;
tempCol = col-row;
}
while (tempRow != N-1 && tempCol != N-1) {
if (tempRow == row && tempCol ==col ){
//no need to check
} else if(queen(tempRow,tempCol) == 1 ) {
return true;
}
tempRow++;
tempCol++;
}
//algorithm to check right diagonal
if (row + col >= N-1) {
tempCol = N-1;
tempRow = (row + col) -(N-1)
} else {
tempRow = 0;
tempCol = row + col;
}
while (tempRow != N-1 && tempCol != 0) {
if (tempRow == row && tempCol ==col ) {
//no need to check
} else if(queen(tempRow,tempCol) == 1 ) {
return true;
}
tempRow++;
tempCol--;
}
return false;
}