Follow up for N-Queens problem.
Now, instead outputting board configurations, return the total number of distinct solutions.
题目链接:https://leetcode.com/problems/n-queens-ii/
题目分析:求n皇后有多少不同解,采用深度优先搜索,对每行枚举列并判断
public class Solution {
public boolean judge(int n, int row, int col, int[][] board) {
for (int i = 0; i < row; i ++) {
if(board[i][col] == 1) {
return false;
}
}
for (int i = 0; i <= row; i ++) {
if(row - i >= 0 && col - i >= 0) {
if(board[row - i][col - i] == 1) {
return false;
}
}
}
for (int i = 0; i <= row; i ++) {
if(row - i >= 0 && col + i < n) {
if(board[row - i][col + i] == 1) {
return false;
}
}
}
return true;
}
public void DFS(int row, int n, int[][] board, int[] ans) {
if (row == n) {
ans[0] ++;
return;
}
for (int col = 0; col < n; col ++) {
if(judge(n, row, col, board)) {
board[row][col] = 1;
DFS(row + 1, n, board, ans);
board[row][col] = 0;
}
}
}
public int totalNQueens(int n) {
int[] ans = new int[1];
ans[0] = 0;
int[][] board = new int[n][n];
for (int i = 0; i < n; i ++) {
Arrays.fill(board[i], 0);
}
DFS(0, n, board, ans);
return ans[0];
}
}