本文主要是介绍刷代码随想录有感(80):回溯算法——解数独,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题干:
代码:
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是只取一个符合条件的就可。
为什么能够返回填入数字后的结果————因为传入的是地址。
这篇关于刷代码随想录有感(80):回溯算法——解数独的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!