xinyu04

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

[Oracle] LeetCode 37 Sudoku Solver

Write a program to solve a Sudoku puzzle by filling the empty cells.

A sudoku solution must satisfy all of the following rules:

  • Each of the digits 1-9 must occur exactly once in each row.
  • Each of the digits 1-9 must occur exactly once in each column.
  • Each of the digits 1-9 must occur exactly once in each of the 9 3x3 sub-boxes of the grid.

The '.' character indicates empty cells.

Solution

对于每一个空缺的位置,我们需要遍历所有的数字进行 check

check 的时候我们需要对于所在行,所在列,以及小九宫格进行检查,这里注意九宫格检查的写法

点击查看代码
class Solution {
private:
bool check(char c, vector<vector<char>>& board, int row, int col){
for(int i=0;i<9;i++){
if(board[i][col]==c)return false;
if(board[row][i]==c)return false;
if(board[3*(row/3)+i/3][3*(col/3)+i%3]==c)return false;
}
return true;
}
bool dfs(vector<vector<char>>& board){
int nr = board.size(), nc = board.size();
for(int i=0;i<nr;i++){
for(int j=0;j<nc;j++){
if(board[i][j]=='.'){
for(char c = '1';c<='9';c++){
if(check(c,board,i,j)){
board[i][j]=c;
if(dfs(board))return true;
else board[i][j]='.';
}
}
return false;
}
}
}
return true;
}
public:
void solveSudoku(vector<vector<char>>& board) {
dfs(board);
}
};

posted on   Blackzxy  阅读(14)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
点击右上角即可分享
微信分享提示