[LeetCode] N-Queens II
2014-05-04 18:08
295 查看
Total Accepted: 6667 Total
Submissions: 21387
Follow up for N-Queens problem.
Now, instead outputting board configurations, return the total number of distinct solutions.
![](http://www.leetcode.com/wp-content/uploads/2012/03/8-queens.png)
public class Solution {
public int totalNQueens(int n) {
int[] path = new int[n+1];
dfs(path, n, 0);
return path
;
}
public void dfs(int[] path, int n, int level) {
if (level == n) {
path
++;
return;
}
for (int i = 0; i < n; i++) {
path[level] = i;
if (check(path, level)) dfs(path, n, level + 1);
}
}
public boolean check(int[] path, int level) {
for (int i = 0; i < level; i++) {
if ((path[i]==path[level]) || Math.abs(path[i]-path[level]) == (level - i))
return false;
}
return true;
}
}
Submissions: 21387
Follow up for N-Queens problem.
Now, instead outputting board configurations, return the total number of distinct solutions.
![](http://www.leetcode.com/wp-content/uploads/2012/03/8-queens.png)
public class Solution {
public int totalNQueens(int n) {
int[] path = new int[n+1];
dfs(path, n, 0);
return path
;
}
public void dfs(int[] path, int n, int level) {
if (level == n) {
path
++;
return;
}
for (int i = 0; i < n; i++) {
path[level] = i;
if (check(path, level)) dfs(path, n, level + 1);
}
}
public boolean check(int[] path, int level) {
for (int i = 0; i < level; i++) {
if ((path[i]==path[level]) || Math.abs(path[i]-path[level]) == (level - i))
return false;
}
return true;
}
}
相关文章推荐
- leetcode[52]:N-Queens II
- 【LeetCode】N-Queens && N-Queens II
- LeetCode 52. N-Queens II
- 【一天一道LeetCode】#52. N-Queens II
- Leetcode---N-Queens II
- LeetCode N-Queens II
- [LeetCode]N-Queens II
- LeetCode: N-Queens II
- Leetcode: N-Queens II
- LeetCode No.52 N-Queens II
- LeetCode || N-Queens II
- Leetcode N-Queens II
- LeetCode: N-Queens II
- Leetcode N-Queens II
- 【Leetcode】N-Queens II (Backtracking)
- LeetCode N-Queens II
- Leetcode-N-Queens II
- LeetCode---N-Queens II
- Leetcode -- N_Queens II
- LeetCode52. N-Queens II