2024每日刷题(111)
Leetcode—37. 解数独
实现代码
class Solution {
public:
bool isValid(vector<vector<char>>& board, int row, int col, char c) {
for(int i = 0; i < 9; i++) {
if(board[row][i] == c || board[i][col] == c || board[3 * (row / 3) + i / 3][3 * (col / 3) + i % 3] == c) {
return false;
}
}
return true;
}
void solveSudoku(vector<vector<char>>& board) {
function<bool(int)> dfs = [&](int s) {
if(s == 81) {
return true;
}
int i = s / 9;
int j = s % 9;
if(board[i][j] != '.') {
return dfs(s + 1);
}
for(char c = '1'; c <= '9'; c++) {
if(isValid(board, i, j, c)) {
board[i][j] = c;
if(dfs(s + 1)) {
return true;
}
board[i][j] = '.';
}
}
return false;
};
dfs(0);
}
};
运行结果
之后我会持续更新,如果喜欢我的文章,请记得一键三连哦,点赞关注收藏,你的每一个赞每一份关注每一次收藏都将是我前进路上的无限动力 !!!↖(▔▽▔)↗感谢支持!