LeetCode-52. N-Queens IIhttps://leetcode.com/problems/n-queens-ii/
题目描述
The n-queens puzzle is the problem of placing n
queens on an n x n
chessboard such that no two queens attack each other.
Given an integer n
, return the number of distinct solutions to the n-queens puzzle.
Example 1:
Input: n = 4 Output: 2 Explanation: There are two distinct solutions to the 4-queens puzzle as shown.
Example 2:
Input: n = 1 Output: 1
Constraints:
1 <= n <= 9
解题思路
【C++】
class Solution {
public:
int totalNQueens(int n) {
if (n == 0) {return 0;}
vector<string> board(n, string(n, '.'));
vector<bool> column(n, false), ldiag(2*n-1, false), rdiag(2*n-1, false);
return backtracking(board, column, ldiag, rdiag, 0, n);
}
int backtracking(vector<string>& board,
vector<bool>& column, vector<bool>& ldiag, vector<bool>& rdiag,
int row, int n) {
if (row == n) {
return 1;
}
int count = 0;
for (int i = 0; i < n; i++) {
if (column[i] || ldiag[n-1-row+i] || rdiag[row+i]) {
continue;
}
board[row][i] = 'Q';
column[i] = ldiag[n-1-row+i] = rdiag[row+i] = true;
count += backtracking(board, column, ldiag, rdiag, row + 1, n);
board[row][i] = '.';
column[i] = ldiag[n-1-row+i] = rdiag[row+i] = false;
}
return count;
}
};
【Java】
class Solution {
public int totalNQueens(int n) {
if (n == 0) {return 0;}
char[][] board = initBoard(n);
boolean[] column = new boolean[n];
boolean[] ldiag = new boolean[2*n-1];
boolean[] rdiag = new boolean[2*n-1];
return backtracking(board, column, ldiag, rdiag, 0, n);
}
private char[][] initBoard(int n) {
char[][] board = new char[n][n];
for (char[] str: board) {Arrays.fill(str, '.');}
return board;
}
int backtracking(char[][] board,
boolean[] column, boolean[] ldiag, boolean[] rdiag,
int row, int n) {
if (row == n) {
return 1;
}
int count = 0;
for (int i = 0; i < n; i++) {
if (column[i] || ldiag[n-1-row+i] || rdiag[row+i]) {
continue;
}
board[row][i] = 'Q';
column[i] = ldiag[n-1-row+i] = rdiag[row+i] = true;
count += backtracking(board, column, ldiag, rdiag, row + 1, n);
board[row][i] = '.';
column[i] = ldiag[n-1-row+i] = rdiag[row+i] = false;
}
return count;
}
}