Home
About
Blog
Products
Forum
Support
Contact
Sunbelt Computer Software
PL/B Language Development and Support
Home
About
Blog
Products
Forum
Support
Contact
Java/src/main/java/com/thealgorithms/backtracking/NQueens.java at master · datpp/Java · GitHub
Skip to content
Navigation Menu
Sign in
Products
Platform
GitHub
Repository hosting, code review, and collaboration
Copilot
AI coding agent for tasks, projects, and automated work
Build & Ship
Actions
CI/CD and automation
Code Quality
Quality analysis, fixes, and enforcement
Codespaces
Cloud development environments
Secure
Code Security
Vulnerability detection and remediation
Secret Protection
Secret scanning and leak prevention
All Features
Developers
Learn
Documentation
Training
Certifications
Build
Build with Copilot
Customize Copilot
Integrations
Explore
Trending repos
GitHub Sponsors
Developer articles
Changelog
Changelog
Your source for the latest features, improvements, and fixes across GitHub products, all in one place.
Businesses
By Stage
Enterprises
Small and medium teams
Startups
Nonprofits
By Industry
Healthcare
Financial services
Manufacturing
Government
See all industries
Evaluate GitHub
Why GitHub
Customer Stories
Business insights
Trust Center
Add-ons
GitHub Advanced Security
Enterprise-grade code security
Copilot for business
Enterprise-grade AI features
Premium Support
Enterprise-grade 24/7 support
Resources
Learn & Connect
Documentation
Resource center
Blog
Events & webinars
Community Forum
Customer Stories
Integrations
Support
Customer support
Training
GitHub Status
Company
About
Partners
Changelog
GitHub Universe
GitHub Universe
The event for developers, by developers — talks, workshops, and what’s next for GitHub.
Pricing
Search
/
Sign in
Sign up
Appearance settings
You signed in with another tab or window.
Reload
to refresh your session.
You signed out in another tab or window.
Reload
to refresh your session.
You switched accounts on another tab or window.
Reload
to refresh your session.
Dismiss alert
{{ message }}
datpp
Java
Repository navigation
Code
Pull requests
Actions
Projects
Security and quality
Insights
More
items
Files
Expand file tree
master
Breadcrumbs
Java
/
src
/
main
/
java
/
com
/
thealgorithms
/
backtracking
/
NQueens.java
Copy path
Blame
More file actions
Blame
More file actions
Latest commit
History
History
History
127 lines (109 loc) · 4.8 KB
master
Breadcrumbs
Java
/
src
/
main
/
java
/
com
/
thealgorithms
/
backtracking
/
NQueens.java
Copy path
Top
File metadata and controls
Code
Blame
127 lines (109 loc) · 4.8 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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
package
com
.
thealgorithms
.
backtracking
;
import
java
.
util
.
ArrayList
;
import
java
.
util
.
HashSet
;
import
java
.
util
.
List
;
import
java
.
util
.
Set
;
/**
* Problem statement: Given a N x N chess board. Return all arrangements in
* which N queens can be placed on the board such no two queens attack each
* other. Ex. N = 6 Solution= There are 4 possible ways Arrangement: 1 ".Q....",
* "...Q..", ".....Q", "Q.....", "..Q...", "....Q."
*
* Arrangement: 2 "..Q...", ".....Q", ".Q....", "....Q.", "Q.....", "...Q.."
*
* Arrangement: 3 "...Q..", "Q.....", "....Q.", ".Q....", ".....Q", "..Q..."
*
* Arrangement: 4 "....Q.", "..Q...", "Q.....", ".....Q", "...Q..", ".Q...."
*
* Solution: Brute Force approach:
*
* Generate all possible arrangement to place N queens on N*N board. Check each
* board if queens are placed safely. If it is safe, include arrangement in
* solution set. Otherwise, ignore it
*
* Optimized solution: This can be solved using backtracking in below steps
*
* Start with first column and place queen on first row Try placing queen in a
* row on second column If placing second queen in second column attacks any of
* the previous queens, change the row in second column otherwise move to next
* column and try to place next queen In case if there is no rows where a queen
* can be placed such that it doesn't attack previous queens, then go back to
* previous column and change row of previous queen. Keep doing this until last
* queen is not placed safely. If there is no such way then return an empty list
* as solution
*/
/*
* Time Complexity: O(N!)
* space Complexity: O(N)
*/
public
final
class
NQueens
{
// Store occupied rows for constant time safety check
private
static
final
Set
<
Integer
>
OCROWS
=
new
HashSet
<>();
// Store occupied main diagonals (row - column)
private
static
final
Set
<
Integer
>
OCDIAG
=
new
HashSet
<>();
// Store occupied anti-diagonals (row + columns)
private
static
final
Set
<
Integer
>
OCANTIDIAG
=
new
HashSet
<>();
private
NQueens
() {
}
public
static
List
<
List
<
String
>>
getNQueensArrangements
(
int
queens
) {
List
<
List
<
String
>>
arrangements
=
new
ArrayList
<>();
getSolution
(
queens
,
arrangements
,
new
int
[
queens
],
0
);
return
arrangements
;
}
public
static
void
placeQueens
(
final
int
queens
) {
List
<
List
<
String
>>
arrangements
=
new
ArrayList
<>();
getSolution
(
queens
,
arrangements
,
new
int
[
queens
],
0
);
if
(
arrangements
.
isEmpty
()) {
System
.
out
.
println
(
" no way to place "
+
queens
+
" queens on board of size "
+
queens
+
"x"
+
queens
);
}
else
{
System
.
out
.
println
(
"Arrangement for placing "
+
queens
+
" queens"
);
}
for
(
List
<
String
>
arrangement
:
arrangements
) {
arrangement
.
forEach
(
System
.
out
::
println
);
System
.
out
.
println
();
}
}
/**
* This is backtracking function which tries to place queen recursively
*
* @param boardSize: size of chess board
* @param solutions: this holds all possible arrangements
* @param columns: columns[i] = rowId where queen is placed in ith column.
* @param columnIndex: This is the column in which queen is being placed
*/
private
static
void
getSolution
(
int
boardSize
,
List
<
List
<
String
>>
solutions
,
int
[]
columns
,
int
columnIndex
) {
if
(
columnIndex
==
boardSize
) {
// this means that all queens have been placed
List
<
String
>
sol
=
new
ArrayList
<>();
for
(
int
i
=
0
;
i
<
boardSize
;
i
++) {
StringBuilder
sb
=
new
StringBuilder
();
for
(
int
j
=
0
;
j
<
boardSize
;
j
++) {
sb
.
append
(
j
==
columns
[
i
] ?
"Q"
:
"."
);
}
sol
.
add
(
sb
.
toString
());
}
solutions
.
add
(
sol
);
return
;
}
// This loop tries to place queen in a row one by one
for
(
int
rowIndex
=
0
;
rowIndex
<
boardSize
;
rowIndex
++) {
columns
[
columnIndex
] =
rowIndex
;
// Skip current position if row or diagonal is already occupied
boolean
isROp
=
OCROWS
.
contains
(
rowIndex
);
boolean
isDOp
=
OCDIAG
.
contains
(
rowIndex
-
columnIndex
) ||
OCANTIDIAG
.
contains
(
rowIndex
+
columnIndex
);
if
(
isROp
||
isDOp
) {
continue
;
}
// Mark current row and diagonal as occupied
OCROWS
.
add
(
rowIndex
);
OCDIAG
.
add
(
rowIndex
-
columnIndex
);
OCANTIDIAG
.
add
(
rowIndex
+
columnIndex
);
// Move to the next column after placing current queen
getSolution
(
boardSize
,
solutions
,
columns
,
columnIndex
+
1
);
// Backtrack by removing current queen
OCROWS
.
remove
(
rowIndex
);
OCDIAG
.
remove
(
rowIndex
-
columnIndex
);
OCANTIDIAG
.
remove
(
rowIndex
+
columnIndex
);
}
}
}
You can’t perform that action at this time.