FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
coding-interview-patterns/java/Backtracking/NQueens.java at main · ByteByteGoHq/coding-interview-patterns · GitHub
Uh oh!
There was an error while loading.
Please reload this page
.
ByteByteGoHq
/
coding-interview-patterns
Public
Notifications
You must be signed in to change notification settings
Fork
304
Star
1.3k
Code
Issues
0
Pull requests
5
Actions
Projects
Security and quality
0
Insights
Additional navigation options
Code
Issues
Pull requests
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
coding-interview-patterns
/
java
/
Backtracking
/
NQueens.java
Copy path
More file actions
More file actions
Latest commit
History
History
History
41 lines (38 loc) · 1.54 KB
Breadcrumbs
coding-interview-patterns
/
java
/
Backtracking
/
NQueens.java
Copy path
File metadata and controls
41 lines (38 loc) · 1.54 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
import
java
.
util
.
HashSet
;
import
java
.
util
.
Set
;
public
class
NQueens
{
int
res
=
0
;
public
int
nQueens
(
int
n
) {
dfs
(
0
,
new
HashSet
<>(),
new
HashSet
<>(),
new
HashSet
<>(),
n
);
return
res
;
}
private
void
dfs
(
int
r
,
Set
<
Integer
>
diagonalsSet
,
Set
<
Integer
>
antiDiagonalsSet
,
Set
<
Integer
>
colsSet
,
int
n
) {
// Termination condition: If we have reached the end of the rows,
// we've placed all 'n' queens.
if
(
r
==
n
) {
res
++;
return
;
}
for
(
int
c
=
0
;
c
<
n
;
c
++) {
int
currDiagonal
=
r
-
c
;
int
currAntiDiagonal
=
r
+
c
;
// If there are queens on the current column, diagonal or
// anti-diagonal, skip this square.
if
(
colsSet
.
contains
(
c
) ||
diagonalsSet
.
contains
(
currDiagonal
) ||
antiDiagonalsSet
.
contains
(
currAntiDiagonal
)) {
continue
;
}
// Place the queen by marking the current column, diagonal, and
// anti−diagonal as occupied.
colsSet
.
add
(
c
);
diagonalsSet
.
add
(
currDiagonal
);
antiDiagonalsSet
.
add
(
currAntiDiagonal
);
// Recursively move to the next row to continue placing queens.
dfs
(
r
+
1
,
diagonalsSet
,
antiDiagonalsSet
,
colsSet
,
n
);
// Backtrack by removing the current column, diagonal, and
// anti−diagonal from the hash sets.
colsSet
.
remove
(
c
);
diagonalsSet
.
remove
(
currDiagonal
);
antiDiagonalsSet
.
remove
(
currAntiDiagonal
);
}
}
}
Back
|
FazBrowse Home
|
New Git URL