Skip to content

Commit 11ce76d

Browse files
refactor 52
1 parent 8eb2c3a commit 11ce76d

File tree

1 file changed

+31
-35
lines changed
  • src/main/java/com/fishercoder/solutions

1 file changed

+31
-35
lines changed
Lines changed: 31 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -1,44 +1,40 @@
11
package com.fishercoder.solutions;
22

3-
/**
4-
* 52. N-Queens II
5-
*
6-
* Follow up for N-Queens problem.
7-
* Now, instead outputting board configurations, return the total number of distinct solutions.
8-
*/
93
public class _52 {
104

11-
public static class Solution1 {
12-
/**credit: https://discuss.leetcode.com/topic/29626/easiest-java-solution-1ms-98-22*/
13-
int count = 0;
5+
public static class Solution1 {
6+
/**
7+
* credit: https://discuss.leetcode.com/topic/29626/easiest-java-solution-1ms-98-22
8+
*/
9+
int count = 0;
1410

15-
public int totalNQueens(int n) {
16-
boolean[] cols = new boolean[n];
17-
boolean[] diagnol = new boolean[2 * n];
18-
boolean[] antiDiagnol = new boolean[2 * n];
19-
backtracking(0, cols, diagnol, antiDiagnol, n);
20-
return count;
21-
}
11+
public int totalNQueens(int n) {
12+
boolean[] cols = new boolean[n];
13+
boolean[] diagnol = new boolean[2 * n];
14+
boolean[] antiDiagnol = new boolean[2 * n];
15+
backtracking(0, cols, diagnol, antiDiagnol, n);
16+
return count;
17+
}
2218

23-
private void backtracking(int row, boolean[] cols, boolean[] diagnol, boolean[] antiDiagnol,
24-
int n) {
25-
if (row == n) {
26-
count++;
27-
}
28-
for (int col = 0; col < n; col++) {
29-
int x = col - row + n;
30-
int y = col + row;
31-
if (cols[col] || diagnol[x] || antiDiagnol[y]) {
32-
continue;
19+
private void backtracking(int row, boolean[] cols, boolean[] diagnol, boolean[] antiDiagnol,
20+
int n) {
21+
if (row == n) {
22+
count++;
23+
}
24+
for (int col = 0; col < n; col++) {
25+
int x = col - row + n;
26+
int y = col + row;
27+
if (cols[col] || diagnol[x] || antiDiagnol[y]) {
28+
continue;
29+
}
30+
cols[col] = true;
31+
diagnol[x] = true;
32+
antiDiagnol[y] = true;
33+
backtracking(row + 1, cols, diagnol, antiDiagnol, n);
34+
cols[col] = false;
35+
diagnol[x] = false;
36+
antiDiagnol[y] = false;
37+
}
3338
}
34-
cols[col] = true;
35-
diagnol[x] = true;
36-
antiDiagnol[y] = true;
37-
backtracking(row + 1, cols, diagnol, antiDiagnol, n);
38-
cols[col] = false;
39-
diagnol[x] = false;
40-
antiDiagnol[y] = false;
41-
}
4239
}
43-
}
4440
}

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy