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

Commit8bff680

Browse files
author
applewjg
committed
add iteration solution
Change-Id: Ic427cd78746a2a3234c4f75d7b153086f999af17
1 parentaed6fa2 commit8bff680

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
publicclassSolution {
3131
publicinttotalNQueens(intn) {
32-
returntotalNQueens_2(n);
32+
returntotalNQueens_3(n);
3333
}
3434
publicinttotalNQueens_1(intn) {
3535
int[]board =newint[n];
@@ -76,4 +76,28 @@ public void totalNQueensRe2(int n, int row, int ld, int rd, int[] res) {
7676
}
7777
}
7878
}
79+
publicinttotalNQueens_3(intn) {
80+
int[]a =newint[n];
81+
Arrays.fill(a,-1);
82+
intres =0;
83+
introw =0;
84+
while (row >=0) {
85+
if (row ==n) {
86+
res++;row--;
87+
}
88+
inti =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+
returnres;
102+
}
79103
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp