52. N-Queens II

52. N-Queens II

Question

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.

Solution

和昨天的题目51. N-Queens一样。
只是不需要转换并记录字符串了,递归结束时直接将res+1即可。

Code

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
35
36
37
38
class Solution {
int target;
int res;
int[][] operations;
public int totalNQueens(int n) {
target = n;
res = 0;
operations = new int[][]{{-1,0},{-1,1},{-1,-1}};
backtracking(new int[n][n], 0, 0);
return res;
}

private void backtracking(int[][] board, int i, int n){
if(n == target){
res++;
return;
}
for(int j = 0; j < target; j++){
if(isValid(board, i, j)){
board[i][j] = 1;
backtracking(board, i+1, n+1);
board[i][j] = 0;
}
}
}

private boolean isValid(int[][] board, int i, int j){
for(int[] operation : operations){
int p = i + operation[0], q = j + operation[1];
while(p >= 0 && p < target && q >= 0 && q < target){
if(board[p][q] == 1) return false;
p += operation[0];
q += operation[1];
}
}
return true;
}
}
Author

Xander

Posted on

2022-06-05

Updated on

2022-06-05

Licensed under

Comments