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

Commitaed6fa2

Browse files
author
applewjg
committed
N-Queen II
Change-Id: I0cea47edcf32d09b399de1f4b946c67b17f69e17
1 parentd002bfe commitaed6fa2

File tree

1 file changed

+79
-0
lines changed

1 file changed

+79
-0
lines changed

‎N-QueensII.java

Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
/*
2+
Author: King, nkuwjg@gmail.com
3+
Date: Aug 23, 2013
4+
Problem: N-Queens II
5+
Difficulty: Medium
6+
Source: https://oj.leetcode.com/problems/n-queens-ii/
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: 1. Recursion.
26+
2. Recursion + bit version. (fast)
27+
The idea is from http://www.matrix67.com/blog/archives/266 (in chinese).
28+
*/
29+
30+
publicclassSolution {
31+
publicinttotalNQueens(intn) {
32+
returntotalNQueens_2(n);
33+
}
34+
publicinttotalNQueens_1(intn) {
35+
int[]board =newint[n];
36+
Arrays.fill(board,-1);
37+
int[]res =newint[1];
38+
totalNQueensRe(n,0,board,res);
39+
returnres[0];
40+
}
41+
publicvoidtotalNQueensRe(intn,introw,int[]board,int[]res) {
42+
if (n ==row) {
43+
res[0]++;
44+
return;
45+
}
46+
for (inti =0;i <n; ++i) {
47+
if (isValid(board,row,i)) {
48+
board[row] =i;
49+
totalNQueensRe(n,row +1,board,res);
50+
board[row] = -1;
51+
}
52+
}
53+
}
54+
publicbooleanisValid(int[]board,introw,intcol) {
55+
for (inti =0;i <row; ++i) {
56+
if (board[i] ==col ||row -i ==Math.abs(col -board[i]))
57+
returnfalse;
58+
}
59+
returntrue;
60+
}
61+
publicinttotalNQueens_2(intn) {
62+
int[]res =newint[1];
63+
totalNQueensRe2(n,0,0,0,res);
64+
returnres[0];
65+
}
66+
publicvoidtotalNQueensRe2(intn,introw,intld,intrd,int[]res) {
67+
if (row == (1<<n) -1 ) {
68+
res[0]++;
69+
return;
70+
}
71+
intavail = ~(row |ld |rd);
72+
for (inti =n -1;i >=0; --i) {
73+
intpos =1<<i;
74+
if ((int)(avail&pos) !=0) {
75+
totalNQueensRe2(n,row |pos, (ld|pos) <<1, (rd|pos) >>1,res);
76+
}
77+
}
78+
}
79+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp