Saturday, August 22, 2015

N-queens puzzle

The n-queens puzzle is a classic dynamic programming puzzle. The problem of placing n queens on an n×n chessboard such that no two queens attack each other.
Given an integer n, return all distinct solutions to the n-queens puzzle.
Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a queen and an empty space respectively.
For example,
There exist two distinct solutions to the 4-queens puzzle:
[
 [".Q..",  // Solution 1
  "...Q",
  "Q...",
  "..Q."],
 ["..Q.",  // Solution 2
  "Q...",
  "...Q",
  ".Q.."]
]


public static void findAllValidQueenPositions(int k){
/*
* an array indicate the queens' column index position on each row
* e.g. if k = 2, array of 0, 1 means queens are placed at 0,0 and 1,1 cells
*/
int[] pos = new int[k];
for(int r = 0; r<pos.length; r++)
pos[r] = -1;
move(pos, 0);
}

private static void move(int[] pos, int row){
int length = pos.length;
if(row == length){//we finish the whole chess board
System.out.println(Arrays.toString(pos));
return;
}

/*
* go through each col on current row
*/
for(int col = 0; col<length; col++){
if(isValidMove(pos, col, row)){
int[] copy = Arrays.copyOf(pos, length);
copy[row] = col;
move(copy, row+1);
}
}

}


private static boolean isValidMove(int[] pos, int col, int row) {
if(row==0)
return true;
else{
for(int r = 0; r<row; r++){
if(Math.abs(pos[r] - col) == Math.abs(r - row) || pos[r] == col)
return false;
}
}

return true;

}

No comments:

Post a Comment