Donate. I desperately need donations to survive due to my health

Get paid by answering surveys Click here

Click here to donate

Remote/Work from Home jobs

how to recursively find a solution for k queen problem

I'm trying to solve a variation I was given of the N queen problem. My problem is a bit different:

I'm given a board size MxN and a partial solution for k' queens. the final objective is to place k queens on the board without any of them threatening the other. while there are also walls on the board that allow the placement of multiple queens on the same row , column or diagonal. given a board say:

* * Q * * * *
Q * X * Q * X
* * Q * X * *
* * * X * * *
X * X * * * * 

the function will get this board, a row and a column for which this is already a solution of k' queens, k' the current number of queens, and k the final number of queens. ASSUMING you cannot add any more queens for row above the given row: my function should attempt to add queens until k on the row that was given from the "col+1" column to the end of that row and on any other row from "row+1" to the end of the board in any column.

so for the given example the partial solution holds for the 3x5 board, I am only allowed to add queens on: ( (2,5~6) & (3~4,0~6) )

My code is the following:

  private static boolean kQueens(int[][] board, int k, int row, int col, int numOfQueens){

        if(numOfQueens >= k) return true;

        //trying to place a queen in the row at the col+1 ~ row length position.
        // if possible place it and try to place a new one in the next position.
        for (int j = col+1 ; j < board[row].length ; j++ ) {
            if (addQueen(board, row, j)) {
                board[row][j] = QUEEN;
            }
            if(kQueens(board, k, row , j , numOfQueens+1))
        }

    return false;//replace with relevant return statement
}

addQueen is a function that checks if it's possible to add a queen in a given position and still have a partial solution ( i.e. no queens are under threat) any ideas of how to move from the row'th row to the next row and still keep the recursive solution?

** a queen is denoted by the constant QUEEN = 1, a wall by WALL = -1, empty by EMPTY = 0

Comments