首页 文章

N皇后算法中对角线检验算法

提问于
浏览
-3

我试图在python中实现N-Queens问题 . 我需要一些帮助来设计算法,以检查是否给出Queen的位置,检查板上是否有任何其他女王在其对角线上 .

我正在尝试设计一个函数 diagonal_check(board, row, col) ,其中board是数组的N * N矩阵,其中'1'代表女王的存在,而'0'代表缺席 . 我会将函数的数组和位置(行,列)传递给函数 . 如果其对角线上存在任何其他女王,则我的函数必须返回false,否则返回true .

如果有人可以帮助我使用 diagonal_check 函数的算法 . 不寻找任何特定的语言代码 .

2 回答

  • 0

    让左上角为(0,0)

    方形(行,列)的右下方对角线是 col-row+7

    方形(行,列)的右向对角线是 row+col

    只需检查2个皇后是否有相同的 col-row+7row+col 应告诉您2个皇后是否在同一对角线上 . 如果你仍然有点困惑,请查看谷歌的棋盘图像 .

  • 0
    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;
    }
    

相关问题