-3

I am trying to implement N- Queens problem in python. I need a small help in designing the algorithm to check if given a position of Queen check whether any other queen on the board is present on its diagonal or not.

I am trying to design a function diagonal_check(board, row, col) where board is N*N matrix of arrays where '1' represents presence of queen and '0' represents absence. I will pass array and position of queen (row,col) to the function. My function must return false if any other queen is present on its diagonal or else return true.

If anyone could help me with algorithm for diagonal_check function. Not looking for any specific language code.

mkj
  • 2,761
  • 5
  • 24
  • 28
Mihir Thatte
  • 105
  • 1
  • 2
  • 9

2 Answers2

0

Let the top left corner be (0,0)

The down-right oriented diagonal for a square (row,col) is col-row+7

The up-right oriented diagonal for a square (row,col) is row+col

Simply check if 2 queens have the same col-row+7 or row+col should tell you if 2 queens are on the same diagonal. If you still are a bit confused, look up Google for a chessboard image.

Benson Lin
  • 1,394
  • 13
  • 17
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;
}
Seth
  • 1,545
  • 1
  • 16
  • 30
unknown
  • 1
  • 1