Thought:
It is a classic backtracking problem.
Cache stores the column index of each queen in each row.
Check method check the rules of queens.
We first put the first queen in the first row, and if no rules violated, we put the next row, once we have put N queens, update the result.
Code:
public class Solution {
int[] cache;
ArrayList<String[]> result;
public ArrayList<String[]> solveNQueens(int n) {
cache = new int[n];
result = new ArrayList<String[]>();
placeQueen(0, n);
return result;
}
public boolean check(int row) {
for (int i = 0; i < row; i++) {
int dif = Math.abs(cache[i] - cache[row]);
if (dif == 0 || dif == row - i) return false;
}
return true;
}
public void placeQueen(int row, int max) {
if (row == max) {
String[] buffer = new String[max];
for (int i = 0; i < max; i++) {
StringBuilder temp = new StringBuilder();
for (int j = 0; j < max; j++) {
if (cache[i] == j) temp.append("Q");
else temp.append(".");
}
buffer[i] = temp.toString();
}
result.add(buffer);
return;
}
for (int i = 0; i < max; i++) {
cache[row] = i;
if (check(row)) placeQueen(row + 1, max);
}
}
}
No comments:
Post a Comment