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

Uni - app - uview Swiper shuffling figure component, click on the links to jump (click to get the item after the row data, remove data operation)

基于 R 语言的判别分析介绍与实践 LDA和QDA

Do you know the difference between comments, keywords, and identifiers?

The FPGA - work summary recently

联通网管协议框图

How to save Simulink simulation model as image or PDF

Flutter introduction advanced trip (5) Image Widget

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

30行代码实现蚂蚁森林自动偷能量

Unicom network management protocol block diagram
随机推荐
FPGA-在ISE中错误总结(更新中)
ERP不规范,同事两行泪 (转载非原创)
Oracle Recovery Tools修复空闲坏块
基于 R 语言的判别分析介绍与实践 LDA和QDA
LeetCode 37.解数独
GIN文件上传与返回
【FPGA教程案例48】图像案例8——基于FPGA的RGB图像转化为HSV图像的实现,通过MATLAB进行辅助验证
JVM常用监控工具解释以及使用
Rust 入门指南(使用JSON)
kustomize entry example and basic syntax instructions
注:检测到当前使用的ADB不是HBuilder内置或自定义ADB:PID为:9544进程名称为:adb.exe 路径为:c:\users\administrator\appdata\local\and
Professor Chen Qiang's "Machine Learning and R Application" course Chapter 16 Assignment
The FPGA - work summary recently
19、学习MySQL 索引
新起之秀 DPU,正在掀起数据中心变革!
How to save Simulink simulation model as image or PDF
[极客大挑战 2019]Upload
FPGA中串口通信的时钟频率和波特率计数
透明tune proxy
FFmpeg多媒体文件处理(ffmpeg打印音视频Meta信息)