问题描述
Follow up for N-Queens problem.
Now, instead outputting board configurations, return the total number of distinct solutions.
问题分析
和上一题类似,只是输出改成了结果数量,其实比上一题简单。
代码实现
private boolean check(int row, int[] columnForRow) {
for (int i = 0; i < row; i++) {
if (columnForRow[row] == columnForRow[i] || Math.abs(columnForRow[row] - columnForRow[i]) == row - i)
return false;
}
return true;
}
public int totalNQueens(int n) {
ArrayList<Integer> res = new ArrayList<Integer>();
res.add(0);
helper2(n, 0, new int[n], res);
return res.get(0);
}
private void helper2(int n, int row, int[] columnForRow, ArrayList<Integer> res) {
if (row == n) {
res.set(0, res.get(0) + 1);
return;
}
for (int i = 0; i < n; i++) {
columnForRow[row] = i;
if (check(row, columnForRow)) {
helper2(n, row + 1, columnForRow, res);
}
}
}
网友评论