当前位置:网站首页>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;
}
};
边栏推荐
猜你喜欢

联通网管协议框图

Go 事,如何成为一个Gopher ,并在7天找到 Go 语言相关工作,第1篇

Clock frequency and baud rate count for serial communication in FPGA

Redis源码剖析之跳表(skiplist)

Flutter入门进阶之旅(六)Layout Widget

Unicom network management protocol block diagram

5G Unicom Network Management Design Ideas

Flutter入门进阶之旅(三)Text Widgets

The new features of ABP 6.0.0 - rc. 1

Rust from entry to proficient 04 - data types
随机推荐
乐东消防救援大队应邀为干部开展消防安全培训
Flutter Getting Started and Advanced Tour (4) Text Input Widget TextField
Standing wave ratio calculation method
电脑重装系统后桌面图标如何调小尺寸
26. Pipeline parameter substitution command xargs
第六届”蓝帽杯“全国大学生网络安全技能大赛 半决赛
GIN中GET POST PUT DELETE请求
2022年非一线IT行业就业前景?
我的2020年终总结
Extract EventBus encapsulation to base class using annotations
第六届“强网杯”全国网络安全挑战赛
基于 R 语言的判别分析介绍与实践 LDA和QDA
在已打开图片上加水印(文字)
造自己的芯,让谷歌买单!谷歌再度开源 180nm 工艺的芯片
ARM board adds routing function
ctfshow七夕杯2022
5G China unicom 直放站 网管协议 实时性要求
[FPGA Tutorial Case 48] Image Case 8 - Realization of Converting RGB Image to HSV Image Based on FPGA, Assisted Verification by MATLAB
ViewPager fragments of nested data blank page abnormal problem analysis
ftplib+ tqdm upload and download progress bar