# Hard-题目24：37. Sudoku Solver

64人阅读 评论(0)

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

Empty cells are indicated by the character ‘.’.

You may assume that there will be only one unique solution.

class Solution {
public:
void solveSudoku(vector<vector<char>>& board) {
backtrack(board, 0, 0);
}
bool backtrack(vector<vector<char>>& board, int row, int col){
if(row == 9)
return true;
if(col == 9)
return backtrack(board, row+1, 0);
if(board[row][col] != '.')
return backtrack(board, row, col+1);
for(char i='1'; i<='9'; i++){
if(isValid(board, row, col, i)){
board[row][col] = i;
if(backtrack(board, row, col+1))
return true;
board[row][col] = '.';
}
}
return false;
}
bool isValid(vector<vector<char>>& board, int row, int col, char k){
for(int i=0; i<9; i++){
if(board[i][col] == k)
return false;
if(board[row][i] == k)
return false;
}
for(int i=(row/3)*3; i<(row/3)*3+3; i++){
for(int j=(col/3)*3; j<(col/3)*3+3; j++){
if(board[i][j] == k)
return false;
}
}
return true;
}
};

40ms,beats 66.04%,4ms,9.81%

0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：63204次
• 积分：3275
• 等级：
• 排名：第10713名
• 原创：270篇
• 转载：53篇
• 译文：0篇
• 评论：8条
文章分类
阅读排行
最新评论