FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
JavaArithmetic/src/LeetCode/LeetCode51.java at master · git-jhy/JavaArithmetic · GitHub
git-jhy
JavaArithmetic
Repository navigation
Code
Pull requests
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
JavaArithmetic
/
src
/
LeetCode
/
LeetCode51.java
Copy path
More file actions
More file actions
Latest commit
History
History
History
85 lines (67 loc) · 2.26 KB
Breadcrumbs
JavaArithmetic
/
src
/
LeetCode
/
LeetCode51.java
Copy path
File metadata and controls
85 lines (67 loc) · 2.26 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
73
74
75
76
77
78
79
80
81
82
83
84
85
package
LeetCode
;
import
java
.
util
.
ArrayList
;
import
java
.
util
.
Arrays
;
import
java
.
util
.
LinkedList
;
import
java
.
util
.
List
;
public
class
LeetCode51
{
/// 51. N-Queens
/// https://leetcode.com/problems/n-queens/description/
/// 时间复杂度: O(n^n)
/// 空间复杂度: O(n)
private
boolean
[]
col
;
private
boolean
[]
dia1
;
private
boolean
[]
dia2
;
private
ArrayList
<
List
<
String
>>
res
;
public
List
<
List
<
String
>>
solveNQueens
(
int
n
) {
res
=
new
ArrayList
<>();
col
=
new
boolean
[
n
];
dia1
=
new
boolean
[
2
*
n
-
1
];
dia2
=
new
boolean
[
2
*
n
-
1
];
LinkedList
<
Integer
>
row
=
new
LinkedList
<>();
putQueen
(
n
,
0
,
row
);
return
res
;
}
// 尝试在一个n皇后问题中, 摆放第index行的皇后位置
private
void
putQueen
(
int
n
,
int
index
,
LinkedList
<
Integer
>
row
){
if
(
index
==
n
){
res
.
add
(
generateBoard
(
n
,
row
));
return
;
}
for
(
int
i
=
0
;
i
<
n
;
i
++)
// 尝试将第index行的皇后摆放在第i列
if
(!
col
[
i
] && !
dia1
[
index
+
i
] && !
dia2
[
index
-
i
+
n
-
1
]){
row
.
addLast
(
i
);
col
[
i
] =
true
;
dia1
[
index
+
i
] =
true
;
dia2
[
index
-
i
+
n
-
1
] =
true
;
putQueen
(
n
,
index
+
1
,
row
);
col
[
i
] =
false
;
dia1
[
index
+
i
] =
false
;
dia2
[
index
-
i
+
n
-
1
] =
false
;
row
.
removeLast
();
}
return
;
}
private
List
<
String
>
generateBoard
(
int
n
,
LinkedList
<
Integer
>
row
){
assert
row
.
size
() ==
n
;
ArrayList
<
String
>
board
=
new
ArrayList
<
String
>();
for
(
int
i
=
0
;
i
<
n
;
i
++){
char
[]
charArray
=
new
char
[
n
];
Arrays
.
fill
(
charArray
,
'.'
);
charArray
[
row
.
get
(
i
)] =
'Q'
;
board
.
add
(
new
String
(
charArray
));
}
return
board
;
}
private
static
void
printBoard
(
List
<
String
>
board
){
for
(
String
s
:
board
)
System
.
out
.
println
(
s
);
System
.
out
.
println
();
}
public
static
void
main
(
String
[]
args
) {
int
n
=
4
;
List
<
List
<
String
>>
res
= (
new
LeetCode51
()).
solveNQueens
(
n
);
for
(
List
<
String
>
board
:
res
)
printBoard
(
board
);
}
}
Back
|
FazBrowse Home
|
New Git URL