题意:解9*9数独
做法:回溯
对每一个还没填充的格子,尝试1~9这9个数字,如果是合法的,则继续填充下一个格子,否则回溯。
判断合法:只需要判断对应行、对应列、对应3*3,有没有矛盾。
设未被填充的格子个数为n,那么时间复杂度大约为
O(9n+1)=O(9n)
在leetcode上用时76ms,本题在leetcode上有0ms的解法,
2ms解法
0ms解法
class Solution {
public:
void solveSudoku(vector<vector<char>>& board) {
solve(board);
}
private:
bool solve(vector<vector<char>>& board){
for(int i = 0; i < board.size(); ++i)
for(int j = 0; j < board[0].size(); ++j){
if(board[i][j] == '.'){
for(int ch = '1'; ch <= '9'; ++ch)
if(isValid(board, i, j, ch)){
board[i][j] = ch;
if(solve(board)) return true;
else board[i][j] = '.';
}
return false;
}
}
return true;
}
bool isValid(vector<vector<char>>& board, int row, int col, char ch) {
for(int i = 0; i < board.size(); ++i){
int x = row / 3 * 3 + i / 3, y = col / 3 * 3 + i % 3;
if(board[i][col] == ch || board[row][i] == ch || board[x][y] == ch) return false;
}
return true;
}
};