leetcode---N-Queens II
最编程
2024-03-14 20:02:42
...
Follow up for N-Queens problem.
Now, instead outputting board configurations, return the total number of distinct solutions.
class Solution {
public:
int ans = 0;
bool ok(int depth, int col, int n, vector<string> &tmp)
{
int sum = col + depth;
int c = 0;
for(int i=0; i<depth; i++)
{
c = depth - i;
if(tmp[i][col] == 'Q' || tmp[i][sum-i] == 'Q' || tmp[i][col-c] == 'Q')
return false;
}
return true;
}
void dfs(int depth, vector<string> &tmp, int n)
{
if(depth >= n)
{
ans++;
return;
}
for(int j=0; j<n; j++)
{
tmp[depth][j] = 'Q';
if(ok(depth, j, n, tmp))
dfs(depth+1, tmp, n);
tmp[depth][j] = '.';
}
}
int totalNQueens(int n)
{
vector<string> tmp;
for(int i=0; i<n; i++)
{
string s = "";
for(int j=0; j<n; j++)
s += '.';
tmp.push_back(s);
}
dfs(0, tmp, n);
return ans;
}
};
上一篇: 永别了,91.com!宣布永久关闭
下一篇: GMail
推荐阅读
-
注册原则与选择:Zookeeper、Eureka、Nacos、Consul 和 Etcd (II)
-
etcd 实用基础 (II)
-
AirSim Dynamics | 安装和配置 AirSim 环境 (II)
-
飞思卡尔 16 位微控制器(II)--CodeWarrior 开发环境设置和新项目、调试项目
-
解决 iPad 开机卡在白苹果状态的原因和方法列表 - II. iPad 开机一直显示白苹果的解决方法?
-
SQL 语句 (II) 创建带主键和约束的数据表
-
音频文件的常见格式 - II.
-
Excel 图表:精美的 "到达率 "显示(II)--"水位图"!
-
YOLOv5 入门 (II) 处理自己的数据集(标签统计、数据集分区、数据增强)
-
Oracle 程序驻留程序内存优化 [数据库实例优化系列 II]。