-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsolution.java
More file actions
72 lines (68 loc) · 1.69 KB
/
Copy pathsolution.java
File metadata and controls
72 lines (68 loc) · 1.69 KB
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
// 51. N-Queens
// https://leetcode.com/problems/n-queens/
// Hard | Java | Accepted 2025-12-19
// Runtime 3 ms | Memory 46.9 MB
class Solution {
List<List<String>> ans = new ArrayList<>();
int num;
public List<List<String>> solveNQueens(int n) {
char[][] board = new char[n][n];
for(int r = 0; r<n; r++)
{
for(int c = 0; c<n; c++)
{
board[r][c] = '.';
}
}
num = n;
recurse(board, 0);
return ans;
}
public void recurse(char[][] board, int r)
{
if(r==board.length)
{
List<String> res = new ArrayList<>();
for(int l = 0; l<num; l++)
{
res.add(new String(board[l]));
}
ans.add(new ArrayList<>(res));
return;
}
for(int j = 0; j<num; j++)
{
if(isValid(board, r, j))
{
board[r][j] = 'Q';
recurse(board, r+1);
board[r][j] = '.';
}
}
}
public boolean isValid(char[][] board, int r, int c)
{
for(int row = 0; row<r; row++)
{
if(board[row][c]=='Q')
{
return false;
}
}
for(int row1 = r-1, col1 = c-1; row1 >=0 && col1 >=0; row1--, col1--)
{
if(board[row1][col1]=='Q')
{
return false;
}
}
for(int row2 = r-1, col2 = c+1; row2>=0 && col2<board.length; row2--, col2++)
{
if(board[row2][col2]=='Q')
{
return false;
}
}
return true;
}
}