summary:
backtrack
package myapp.kit.leetcode.top200;
import java.util.ArrayList;
import java.util.List;
/**
*
* 52
* hard
* https://leetcode.com/problems/n-queens-ii/
*
* 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 the number of distinct solutions to the n-queens puzzle.
*
* Example:
*
* Input: 4
* Output: 2
* Explanation: There are two distinct solutions to the 4-queens puzzle as shown below.
* [
* [".Q..", // Solution 1
* "...Q",
* "Q...",
* "..Q."],
*
* ["..Q.", // Solution 2
* "Q...",
* "...Q",
* ".Q.."]
* ]
*
*
* @author huangdingsheng
* @version 1.0, 2020/6/29
*/
public class n_queens_ii_52 {
private int answer;
private boolean[] xVisited;
private boolean[] yVisited;
public int totalNQueens(int n) {
answer = 0;
xVisited = new boolean[n];
yVisited = new boolean[n];
search(n, new int[n][n], 0, 0);
return answer;
}
private void search(int n, int[][] board, int count, int depth) {
if (depth > n) {
return;
}
if (count == n) {
// get an answer from current board
answer++;
return;
}
for (int j = 0; j < n; j++) {
if (yVisited[j] || validateSlash(board, depth, j)) {
continue;
}
board[depth][j] = 1;
yVisited[j] = true;
xVisited[depth] = true;
search(n, board, count + 1, depth + 1);
board[depth][j] = 0;
yVisited[j] = false;
xVisited[depth] = false;
}
}
private boolean validateSlash(int[][] board, int x, int y) {
int m = board.length;
int n = board[0].length;
int x1 = x;
int y1 = y;
while (x1 < m - 1 && y1 < n - 1) {
x1++;
y1++;
if (board[x1][y1] == 1) {
return true;
}
}
int x2 = x;
int y2 = y;
while (x2 > 0 && y2 > 0) {
x2--;
y2--;
if (board[x2][y2] == 1) {
return true;
}
}
int x3 = x;
int y3 = y;
while (x3 > 0 && y3 < n - 1) {
x3--;
y3++;
if (board[x3][y3] == 1) {
return true;
}
}
int x4 = x;
int y4 = y;
while (x4 < m - 1 && y4 > 0) {
x4++;
y4--;
if (board[x4][y4] == 1) {
return true;
}
}
return false;
}
private List<String> getAnswerFromBoard(int[][] board) {
List<String> result = new ArrayList<>();
for (int i = 0; i < board.length; i++) {
StringBuilder sb = new StringBuilder();
for (int j = 0; j < board[i].length; j++) {
if (board[i][j] == 1) {
sb.append('Q');
} else {
sb.append('.');
}
}
result.add(sb.toString());
}
return result;
}
}