题干:
代码:
class Solution {
public:
bool backtracking(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 k = '1'; k <= '9'; k++){
if(isvalid(board, k, i, j)){
board[i][j] = k;
if(backtracking(board))return true;
board[i][j] = '.';
}
}
return false;
}
}
}
return true;
}
bool isvalid(vector<vector<char>> &board, char val, int row, int col){
for(int i = 0; i < 9; i++){
if(board[i][col] == val)return false;
}
for(int j = 0; j < 9; j++){
if(board[row][j] == val)return false;
}
int startrow = (row / 3) * 3;
int startcol = (col / 3) * 3;
for(int i = startrow; i < startrow + 3; i++){
for(int j = startcol; j < startcol + 3; j++){
if(board[i][j] == val)return false;
}
}
return true;
}
void solveSudoku(vector<vector<char>>& board) {
backtracking(board);
}
};
注意:
bool backtracking(vector<vector<char>>& board)
for(int i = 0; i < board.size(); i++){//遍历行
for(int j = 0; j < board[0].size(); j++){//遍历列
if(backtracking(board))return true;
for(char k = '1'; k <= '9'; k++){
if(isvalid(board, k, i, j)){
board[i][j] = k;
if(backtracking(board))return true;
board[i][j] = '.';
}
}
return false;//false对应的必须是尝试9个数字都不行的结果
int startrow = (row / 3) * 3;
int startcol = (col / 3) * 3;
for(int i = startrow; i < startrow + 3; i++){
for(int j = startcol; j < startcol + 3; j++){
if(board[i][j] == val)return false;
}
}//小9格检验
对使用bool的解释:思路同路径总和,void是举出所有情况,bool是只取一个符合条件的就可。
为什么能够返回填入数字后的结果————因为传入的是地址。