Skip to content

Commit 8bff680

Browse files
author
applewjg
committed
add iteration solution
Change-Id: Ic427cd78746a2a3234c4f75d7b153086f999af17
1 parent aed6fa2 commit 8bff680

File tree

1 file changed

+26
-2
lines changed

1 file changed

+26
-2
lines changed

N-QueensII.java

Lines changed: 26 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,11 +25,11 @@
2525
Solution: 1. Recursion.
2626
2. Recursion + bit version. (fast)
2727
The idea is from http://www.matrix67.com/blog/archives/266 (in chinese).
28+
3. Iteration.
2829
*/
29-
3030
public class Solution {
3131
public int totalNQueens(int n) {
32-
return totalNQueens_2(n);
32+
return totalNQueens_3(n);
3333
}
3434
public int totalNQueens_1(int n) {
3535
int[] board = new int[n];
@@ -76,4 +76,28 @@ public void totalNQueensRe2(int n, int row, int ld, int rd, int[] res) {
7676
}
7777
}
7878
}
79+
public int totalNQueens_3(int n) {
80+
int[] a = new int[n];
81+
Arrays.fill(a,-1);
82+
int res = 0;
83+
int row = 0;
84+
while (row >= 0) {
85+
if (row == n) {
86+
res++; row--;
87+
}
88+
int i = a[row] == -1 ? 0 : a[row] + 1;
89+
for ( ; i < n; ++i) {
90+
if (isValid(a, row, i)) {
91+
a[row] = i;
92+
row++;
93+
break;
94+
}
95+
}
96+
if (i == n) {
97+
a[row] = -1;
98+
row--;
99+
}
100+
}
101+
return res;
102+
}
79103
}

0 commit comments

Comments
 (0)