Welcome to the Java Programming Forums

The professional, friendly Java community. 21,500 members and growing!

The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.

>> REGISTER NOW TO START POSTING

# Thread: recursion to find a solution for K queen problem (variation)

1. ## recursion to find a solution for K queen problem (variation)

I'm trying to write a function that can take a partial solution to a problem and give a solution. I am given a board of size MxN , where I should attempt to place K queens given a partial solution of K'

for example the following board:

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

the function should take this board, and the indexes 1 for row and 2 for column, the current number of queens on it - 2 and the final number of queens to be on it - 4. I'm only allowed to add queens on the rowth row from the colth column to the end of that row, and any following row for any column in this example - (1,3), (2,0), (2,1), (2,2), (2,3), (3,0), (3,1), (3,2), (3,3) the function should print true because it is possible .. for example the following:

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

however my function doesn't quite do that and I can't see why..

```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 i = 0; i < board.length; ++i) {
for (int j = 0; j < board[i].length; j++) {
//save the value of that position in case we'll need to change it back
int tmp = board[i][j];
board[i][j] = QUEEN;
}
if (kQueens(board, k, i, j, numOfQueens + 1)) {

return true;
}
//remove the queen and backtrack
board[i][j]=tmp;
}
}
return false;
}```