当前位置:网站首页>LeetCode 37. Solve Sudoku
LeetCode 37. Solve Sudoku
2022-08-09 13:49:00 【A pig to】
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;
}
};
边栏推荐
- 陈强教授《机器学习及R应用》课程 第十四章作业
- 注:检测到当前使用的ADB不是HBuilder内置或自定义ADB:PID为:9544进程名称为:adb.exe 路径为:c:\users\administrator\appdata\local\and
- Map mixed density function and quantile added line
- FFmpeg multimedia file processing (FFMPEG logging system)
- LnReader编译
- Data Mining-06
- 面试题精选:神奇的斐波那契数列
- 在已打开图片上加水印(文字)
- 记录本项目中用到的系统调用与C库函数-2
- GET POST PUT DELETE request in GIN
猜你喜欢
随机推荐
剑指 Offer 43. 1~n 整数中 1 出现的次数(递归、数学)
ViewPager fragments of nested data blank page abnormal problem analysis
The sword refers to the offer, cuts the rope 2
[HCIP Continuous Update] Principle and Configuration of IS-IS Protocol
read stream special attention
中断系统结构及中断控制详解
2022年非一线IT行业就业前景?
生成上传密钥和密钥库
novel research
GIN a preliminary study, the environment is installed
造自己的芯,让谷歌买单!谷歌再度开源 180nm 工艺的芯片
新起之秀 DPU,正在掀起数据中心变革!
Flutter Getting Started and Advanced Tour (4) Text Input Widget TextField
glibc memory management model freeing C library memory cache
Oracle Recovery Tools修复空闲坏块
透明tune proxy
Redis源码剖析之robj(redisObject)
Yocto 可以下载的第三方库
Redis源码剖析之跳表(skiplist)
工作任务统计








