当前位置:网站首页>LeetCode 37.解数独
LeetCode 37.解数独
2022-08-09 12:45:00 【养猪去】
class Solution {
public:
void solveSudoku(vector<vector<char>>& board) {
pair<int,int> p = getNext(board);
int sx = p.first,sy = p.second;
dfs(sx,sy,board);
}
bool dfs(int x,int y,vector<vector<char>>& board){
if(isFinished(board)) {
return true;
}
for(int n=1;n<=9;n++){
board[x][y] = char(n+'0');
if(isValidSudoku(board)){
pair<int,int> p = getNext(board);
int sx = p.first,sy = p.second;
if(dfs(sx,sy,board)){
return true;
}
}
}
board[x][y] = '.';
return false;
}
pair<int,int> getNext(vector<vector<char>>& board) {
int sx=-1,sy=-1;
for(int i=0;i<9;i++){
if(sx!=-1){
break;
}
for(int j=0;j<9;j++){
if(board[i][j]=='.'){
sx = i, sy = j;
break;
}
}
}
return make_pair(sx,sy);
}
bool isFinished(vector<vector<char>>& board){
for(int i=0;i<9;i++){
for(int j=0;j<9;j++){
if(board[i][j]=='.'){
return false;
}
}
}
return true;
}
bool isValidSudoku(vector<vector<char>>& board) {
bool rv[9][10]={
0},cv[9][10]={
0},gv[9][10]={
0};
for(int i=0;i<9;i++){
for(int j=0;j<9;j++){
if(board[i][j]=='.') {
continue;
}
int v = board[i][j]-'0';
if(rv[i][v] || cv[j][v] || gv[i/3*3+j/3][v]){
return false;
}
rv[i][v] = 1;
cv[j][v] = 1;
gv[ i/3*3+j/3 ][v] = 1;
}
}
return true;
}
};
边栏推荐
猜你喜欢
Flutter Getting Started and Advanced Tour (4) Text Input Widget TextField
某高校的R语言数据分析期末作业
在“Extend the Omniverse”比赛中构建用于 3D 世界的工具
Flutter Getting Started and Advanced Tour (3) Text Widgets
ViewPager fragments of nested data blank page abnormal problem analysis
绘制混合密度函数图以及添加分位数线
新起之秀 DPU,正在掀起数据中心变革!
电脑重装系统还原0x80070005错误如何解决
kustomize entry example and basic syntax instructions
Flutter入门进阶之旅(三)Text Widgets
随机推荐
Redis源码剖析之字典(dict)
陈强教授《机器学习及R应用》课程 第十三章作业
ARM板卡增加路由功能
Flutter入门进阶之旅(六)Layout Widget
Report: The number of students who want to learn AI has increased by 200%, and there are not enough teachers
面试题精选:神奇的斐波那契数列
陈强教授《机器学习及R应用》课程 第十四章作业
联通网管协议框图
FFmpeg多媒体文件处理(ffmpeg打印音视频Meta信息)
Flutter Getting Started and Advanced Tour (1) - Getting to Know Flutter
注释、关键字、标识符的区别你知道吗?
How to reduce the size of desktop icons after the computer is reinstalled
阿里大淘系模型治理阶段性分享
ansible-cmdb friendly display ansible collects host information
GIN Bind模式获取参数和表单验证
在“Extend the Omniverse”比赛中构建用于 3D 世界的工具
某高校的R语言数据分析期末作业
Jenkins API groovy调用实践: Jenkins Core Api & Job DSL创建项目
Bitmaps and bit operations
ftplib+ tqdm upload and download progress bar