Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commitd002bfe

Browse files
author
applewjg
committed
N-Queens
Change-Id: I73c0cd91109752c69f790ed4aa71fa3c924555bc
1 parentdc8725f commitd002bfe

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, nkuwjg@gmail.com
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+
publicclassSolution {
30+
publicList<String[]>solveNQueens(intn) {
31+
List<String[]>res =newArrayList<String[]>();
32+
List<char[]>sol =newArrayList<char[]>();
33+
solveNQueensRe(n,0,0,0,sol,res);
34+
returnres;
35+
}
36+
publicvoidsolveNQueensRe(intn,introw,intld,intrd,List<char[]>sol,List<String[]>res) {
37+
if (row == (1<<n) -1 ) {
38+
String[]temp =newString[n];
39+
for (inti =0;i <n; ++i)
40+
temp[i] =String.valueOf(sol.get(i));
41+
res.add(temp);
42+
return;
43+
}
44+
intavail = ~(row |ld |rd);
45+
for (inti =n -1;i >=0; --i) {
46+
intpos =1 <<i;
47+
if ((int)(avail &pos) !=0) {
48+
char[]str =newchar[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)

[8]ページ先頭

©2009-2025 Movatter.jp