Skip to content

Commit d002bfe

Browse files
author
applewjg
committed
N-Queens
Change-Id: I73c0cd91109752c69f790ed4aa71fa3c924555bc
1 parent dc8725f commit d002bfe

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed

N-Queens.java

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
/*
2+
Author: King, [email protected]
3+
Date: Jul 25, 2013
4+
Problem: N-Queens
5+
Difficulty: Medium
6+
Source: https://oj.leetcode.com/problems/n-queens/
7+
Notes:
8+
The n-queens puzzle is the problem of placing n queens on an n*n chessboard such that no two queens attack each other.
9+
Given an integer n, return all distinct solutions to the n-queens puzzle.
10+
Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a queen and an empty space respectively.
11+
For example,
12+
There exist two distinct solutions to the 4-queens puzzle:
13+
[
14+
[".Q..", // Solution 1
15+
"...Q",
16+
"Q...",
17+
"..Q."],
18+
19+
["..Q.", // Solution 2
20+
"Q...",
21+
"...Q",
22+
".Q.."]
23+
]
24+
25+
Solution: Recursion (DFS). Use bit-manipulation solution (See N-QueensII for more details).
26+
*/
27+
28+
29+
public class Solution {
30+
public List<String[]> solveNQueens(int n) {
31+
List<String[]> res = new ArrayList<String[]>();
32+
List<char[]> sol = new ArrayList<char[]>();
33+
solveNQueensRe(n, 0, 0, 0, sol, res);
34+
return res;
35+
}
36+
public void solveNQueensRe(int n, int row, int ld, int rd, List<char[]> sol, List<String[]> res) {
37+
if (row == (1<<n) -1 ) {
38+
String[] temp = new String[n];
39+
for (int i = 0; i < n; ++i)
40+
temp[i] = String.valueOf(sol.get(i));
41+
res.add(temp);
42+
return;
43+
}
44+
int avail = ~(row | ld | rd);
45+
for (int i = n -1; i >= 0; --i) {
46+
int pos = 1 << i;
47+
if ((int)(avail & pos) != 0) {
48+
char[] str = new char[n];
49+
Arrays.fill(str, '.');
50+
str[i] = 'Q';
51+
sol.add(str);
52+
solveNQueensRe(n, row | pos, (ld|pos)<<1, (rd|pos)>>1, sol, res);
53+
sol.remove(sol.size()-1);
54+
}
55+
}
56+
}
57+
}

0 commit comments

Comments
 (0)