Skip to content

Commit 3d64419

Browse files
committed
N-Queens
1 parent 9502964 commit 3d64419

File tree

1 file changed

+77
-0
lines changed

1 file changed

+77
-0
lines changed

NQueens.java

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
/**
2+
* The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.
3+
*
4+
* Given an integer n, return all distinct solutions to the n-queens puzzle.
5+
*
6+
* Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a queen and an empty space respectively.
7+
*
8+
* For example,
9+
*
10+
* There exist two distinct solutions to the 4-queens puzzle:
11+
*
12+
* [
13+
* [".Q..", // Solution 1
14+
* "...Q",
15+
* "Q...",
16+
* "..Q."],
17+
*
18+
* ["..Q.", // Solution 2
19+
* "Q...",
20+
* "...Q",
21+
* ".Q.."]
22+
* ]
23+
*/
24+
25+
import java.util.ArrayList;
26+
27+
public class NQueens {
28+
public ArrayList<String[]> solveNQueens(int n) {
29+
ArrayList<String[]> ret = new ArrayList<String[]>();
30+
if (n == 0)
31+
return ret;
32+
StringBuffer line = new StringBuffer();
33+
for (int i = 0; i < n; i++) {
34+
line.append('.');
35+
}
36+
StringBuffer[] sol = new StringBuffer[n];
37+
for (int i = 0; i < n; i++) {
38+
sol[i] = new StringBuffer(line.toString());
39+
}
40+
boolean[] cols = new boolean[n];
41+
int[] row = new int[n];
42+
findSolutions(n, 0, ret, sol, row, cols);
43+
return ret;
44+
}
45+
46+
private void findSolutions(int n, int start, ArrayList<String[]> ret,
47+
StringBuffer[] sol, int[] row, boolean[] cols) {
48+
if (start == n) {
49+
String[] newSol = new String[n];
50+
for (int i = 0; i < n; i++) {
51+
newSol[i] = sol[i].toString();
52+
}
53+
ret.add(newSol);
54+
} else {
55+
for (int i = 0; i < n; i++) {
56+
if (cols[i])
57+
continue;
58+
boolean ok = true;
59+
for (int j = 0; j < start; j++) {
60+
if (Math.abs(start - j) == Math.abs(i - row[j])) {
61+
ok = false;
62+
break;
63+
}
64+
}
65+
if (ok) {
66+
cols[i] = true;
67+
sol[start].setCharAt(i, 'Q');
68+
row[start] = i;
69+
findSolutions(n, start + 1, ret, sol, row, cols);
70+
row[start] = 0;
71+
sol[start].setCharAt(i, '.');
72+
cols[i] = false;
73+
}
74+
}
75+
}
76+
}
77+
}

0 commit comments

Comments
 (0)