Skip to content

Commit aed6fa2

Browse files
author
applewjg
committed
N-Queen II
Change-Id: I0cea47edcf32d09b399de1f4b946c67b17f69e17
1 parent d002bfe commit aed6fa2

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, [email protected]
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+
public class Solution {
31+
public int totalNQueens(int n) {
32+
return totalNQueens_2(n);
33+
}
34+
public int totalNQueens_1(int n) {
35+
int[] board = new int[n];
36+
Arrays.fill(board,-1);
37+
int[] res = new int[1];
38+
totalNQueensRe(n, 0, board, res);
39+
return res[0];
40+
}
41+
public void totalNQueensRe(int n, int row, int[] board, int[] res) {
42+
if (n == row) {
43+
res[0]++;
44+
return;
45+
}
46+
for (int i = 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+
public boolean isValid(int[] board, int row, int col) {
55+
for (int i = 0; i < row; ++i) {
56+
if (board[i] == col || row - i == Math.abs(col - board[i]))
57+
return false;
58+
}
59+
return true;
60+
}
61+
public int totalNQueens_2(int n) {
62+
int[] res = new int[1];
63+
totalNQueensRe2(n, 0, 0, 0, res);
64+
return res[0];
65+
}
66+
public void totalNQueensRe2(int n, int row, int ld, int rd, int[] res) {
67+
if (row == (1<<n) -1 ) {
68+
res[0]++;
69+
return;
70+
}
71+
int avail = ~(row | ld | rd);
72+
for (int i = n - 1; i >= 0; --i) {
73+
int pos = 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)