leetcode笔记:51. n

# Title Difficulty Topic
52 N-Queens II Hard Backtracking

Description

The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.

8-queens

Given an integer n, return the number of distinct solutions to the n-queens puzzle.

Example:

1
2
3
4
5
6
7
8
9
10
11
12
Input: 4
Output: [
[".Q..", // Solution 1
"...Q",
"Q...",
"..Q."],

["..Q.", // Solution 2
"Q...",
"...Q",
".Q.."]
]

Backtracking

LeetCode 51. N-Queens - 花花酱 刷题找工作 EP41视频里讲的很清晰。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
class  {
private int res = 0;
private int size;

public int totalNQueens(int n) {
size = n;
boolean[][] board = new boolean[n][n];
dfs(board, 0);
return res;
}

public void dfs(boolean[][] board, int row) {
if(row == size) {
res++;
return;
}
for(int j=0; j<size; j++) {
if(isValid(board, row, j)) {
board[row][j] = true;
dfs(board, row+1);
board[row][j] = false;
}
}
}

public boolean isValid(boolean[][] board, int row, int col) {
for(int j=0; j<size; j++) {
if(board[j][col]) return false;
if(row+col-j >= 0 && row+col-j < size && board[row+col-j][j]) return false;
if(row-col+j >= 0 && row-col+j < size && board[row-col+j][j]) return false;
}
return true;
}
}