class Solution {
public:
void solveSudoku(vector<vector<char>>& board) {
if (board.empty() || board.size() == 0) return;
solve(board);
}
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 (char c = '1'; c <= '9'; c++) {
if (is_valid(board, i, j, c)) {
board[i][j] = c;
if (solve(board)) return true;
else board[i][j] = '.';
}
}
return false;
}
}
}
return true;
}
bool is_valid(vector<vector<char>>& board, int& row, int& col, char& c) {
for (int i = 0; i < 9; i++) {
int regionRow = 3 * (row / 3); // region row定位
int regionCol = 3 * (col / 3); // region col定位
if (board[i][col] == c) return false; // 检查row
if (board[row][i] == c) return false; // 检查col
if (board[3 * (row / 3) + i / 3][3 * (col / 3) + i % 3] == c) return false; // 检查3*3方块
}
return true;
}
};
https://leetcode.com/problems/sudoku-solver/
用什么:Backtracking
为什么:一个一个尝试所有解法
思路:
不知道
36, 51