The n-queens puzzle is 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.."] ]N皇后问题的基本思路就是回朔法,往每一个格子放棋子,如果是合法的就继续,如果不合法就撤掉
用一维数组解这种题的时候,可以忽略掉撤掉的情况,因为当用一维数组的时候,只存在放与不放的问题,不存在放与撤掉的问题
代码如下
来自Code_Ganker
public ArrayList<String[]> solveNQueens(int n) {
ArrayList<String[]> result = new ArrayList<String[]>();
if (n <= 0)
return result;
int[] column = new int[n];
helper(n, 0, column, result);
return result;
}
public void helper(int n, int row, int[] column, ArrayList<String[]> result) {
if (n == row) {
String[] temp = new String[n];
for (int i = 0; i < n; i++) {
StringBuilder strRow = new StringBuilder();
for (int j = 0; j < n; j++) {
if (column[i] == j)
strRow.append("Q");
else
strRow.append(".");
}
temp[i] = strRow.toString();
}
result.add(temp);
return;
}
for (int i = 0; i < n; i++) {
column[row] = i;
if (check(row, column))
helper(n, row + 1, column, result);
}
}
public boolean check(int row, int[] column) {
for (int i = 0; i < row; i++) {
if (column[i] == column[row]
|| Math.abs(column[row] - column[i]) == (row - i))
return false;
}
return true;
}