Leetcode: N-Queens II
2016-07-23 10:20
375 查看
N-Queen ||
Follow up for N-Queens problem.
Now, instead outputting board configurations, return the total number of distinct solutions.
Subscribe to see which companies asked this question
N皇后不打印版本。
回溯:以行为基础,row[ i ] 表示 第 i 行的 queen 所在的列号, cal[ i ] 表示 第 i 列是否有皇后 ,判断 对角线 abs(j-r)==abs(row[j]-row[r]) ?1:0 遍历每一种排列情况就可以得到答案
#include<vector>
#include<iostream>
#include<cstdio>
#include<math.h>
#include<string.h>
#include<algorithm>
using namespace std;
class Solution {
public:
int answer;
void solve(int r,int n,int * row,int * cal ){
if(r>n){
answer++;
return;
}
for(int i=1;i<=n;i++){
if(!cal[i]){
cal[i]=1;
row[r]=i;
for(int j=1;j<r;j++){
if(abs(j-r)==abs(row[j]-row[r])){
row[r]=0;
cal[i]=0;
}
}
if(cal[i] && row[r]){
solve(r+1,n,row,cal);
}
row[r]=0;
cal[i]=0;
}
}
}
int totalNQueens(int n) {
answer=0;
int row[n+1];
int cal[n+1];
memset(row,0,sizeof(row));
memset(cal,0,sizeof(cal));
solve(1,n,row,cal);
return answer;
}
};
int main()
{
int answer;
Solution A;
answer=A.totalNQueens(8);
cout<<answer<<endl;
}
Follow up for N-Queens problem.
Now, instead outputting board configurations, return the total number of distinct solutions.
Subscribe to see which companies asked this question
N皇后不打印版本。
回溯:以行为基础,row[ i ] 表示 第 i 行的 queen 所在的列号, cal[ i ] 表示 第 i 列是否有皇后 ,判断 对角线 abs(j-r)==abs(row[j]-row[r]) ?1:0 遍历每一种排列情况就可以得到答案
#include<vector>
#include<iostream>
#include<cstdio>
#include<math.h>
#include<string.h>
#include<algorithm>
using namespace std;
class Solution {
public:
int answer;
void solve(int r,int n,int * row,int * cal ){
if(r>n){
answer++;
return;
}
for(int i=1;i<=n;i++){
if(!cal[i]){
cal[i]=1;
row[r]=i;
for(int j=1;j<r;j++){
if(abs(j-r)==abs(row[j]-row[r])){
row[r]=0;
cal[i]=0;
}
}
if(cal[i] && row[r]){
solve(r+1,n,row,cal);
}
row[r]=0;
cal[i]=0;
}
}
}
int totalNQueens(int n) {
answer=0;
int row[n+1];
int cal[n+1];
memset(row,0,sizeof(row));
memset(cal,0,sizeof(cal));
solve(1,n,row,cal);
return answer;
}
};
int main()
{
int answer;
Solution A;
answer=A.totalNQueens(8);
cout<<answer<<endl;
}
相关文章推荐
- Win2003利用dfs(分布式文件系统)在负载均衡下的文件同步配置方案
- win2003分布式文件系统(dfs)配置方法[图文详解]
- win2003分布式文件系统及其部署 图文教程
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- Hadoop2.6+jdk8的安装部署(1)——使用jar包安装部署【详细】
- Hadoop FS Shell
- DFS使用方法总结
- leetcode----Longest Substring Without Repeating Characters
- FastDFS注意事项
- 无忧技术带您预览DFS(分布式文件系统)管理控制台
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap