|
1 | 1 | package com.fishercoder.solutions;
|
2 | 2 |
|
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 |
| - */ |
9 | 3 | public class _52 {
|
10 | 4 |
|
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; |
14 | 10 |
|
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 | + } |
22 | 18 |
|
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 | + } |
33 | 38 | }
|
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 |
| - } |
42 | 39 | }
|
43 |
| - } |
44 | 40 | }
|
0 commit comments