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

Redis源码剖析之跳表(skiplist)

某高校的R语言数据分析期末作业

造自己的芯,让谷歌买单!谷歌再度开源 180nm 工艺的芯片

Clock frequency and baud rate count for serial communication in FPGA

uni-app - uview Swiper 轮播图组件点击跳转链接(点击后拿到 item 行数据, 取出数据做操作)

WSA工具箱安装应用商店提示无法工作怎么解决?

5G China unicom general exception handling

Flutter introduction advanced trip (5) Image Widget

5G China unicom AP:B SMS ASCII 转码要求

26. Pipeline parameter substitution command xargs
随机推荐
某高校的R语言数据分析期末作业
【TKE】GR+VPC-CNI混用模式下未产品化功能配置
陈强教授《机器学习及R应用》课程 第十五章作业
NFS pays special attention to the problem of permissions
ARM board adds routing function
Standing wave ratio calculation method
Compensation transaction and idempotency guarantee based on CAP components
telnet+ftp to control and upgrade the device
Flutter入门进阶之旅(一)-初识Flutter
[FPGA Tutorial Case 48] Image Case 8 - Realization of Converting RGB Image to HSV Image Based on FPGA, Assisted Verification by MATLAB
在“Extend the Omniverse”比赛中构建用于 3D 世界的工具
数据挖掘-06
5G 联通网管设计思路
Simple encapsulation of glide tool class
陈强教授《机器学习及R应用》课程 第十八章作业
Data Mining-05
自定义VIEW实现应用内消息提醒上下轮播
telnet+ftp 对设备进行 操控 和 升级
ftplib+ tqdm upload and download progress bar
用plot_hist_numeric()实现画直方图