ThinkChat🤖让你学习和工作更高效,注册即送10W Token,即刻开启你的AI之旅 广告
## 一.题目描述 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. The following photo is a sudoku puzzle… ![](https://box.kancloud.cn/2016-01-05_568bb5ee977fb.jpg) …and its solution numbers marked in red: ![](https://box.kancloud.cn/2016-01-05_568bb5eea7cee.jpg) ## 二.题目分析 注意题目说明了输入保证有且只有一个解,所以试探每一个格子的时候,只需要考虑当前行、列、矩形框满足条件,满足就进入下一个格子试探,不满足回溯。 首先,编写一个函数`isValidSudoku()`用于测试矩阵当前坐标的值是否合法,检查当前值在行、列以及`3*3`的矩阵内是否有效。 于是,对于矩阵中的每个空位`'.'`,尝试填入`1~9` 并检查是否合法,正确则往下一个位置递归。 只有正确达到矩阵最右下角位置才算填充成功,此时返回填充结果。 关于**回朔算法**,以下博客写得浅显易懂,可以参考参考: [http://www.cnblogs.com/steven_oyj/archive/2010/05/22/1741376.html](http://www.cnblogs.com/steven_oyj/archive/2010/05/22/1741376.html)  [http://www.cnblogs.com/Creator/archive/2011/05/20/2052341.html](http://www.cnblogs.com/Creator/archive/2011/05/20/2052341.html) ## 三.示例代码 ~~~ #include <iostream> #include <vector> using namespace std; class Solution { public: bool isValidSudoku(vector<vector<char> > &board, int x, int y) { // 同一列中是否出现相同的数 for (int row = 0; row < 9; ++row) if ((x != row) && (board[row][y] == board[x][y])) return false; // 同一行中是否出现相同的数 for (int col = 0; col < 9; ++col) if ((y != col) && (board[x][col] == board[x][y])) return false; // 3 * 3方格中是否出现相同的数 for (int row = (x / 3) * 3; row < (x / 3 + 1) * 3; ++row) for (int col = (y / 3) * 3; col < (y / 3 + 1) * 3; ++col) if ((x != row) && (y != col) && (board[row][col] == board[x][y])) return false; // 满足条件,则返回true return true; } bool internalSolveSudoku(vector<vector<char> > &board) { for (int row = 0; row < 9; ++row) { for (int col = 0; col < 9; ++col) { if (board[row][col] == '.') { for (int i = 1; i <= 9; ++i) { board[row][col] = '0' + i; if (isValidSudoku(board, row, col)) if (internalSolveSudoku(board)) return true; // 若当前格子的数不正确,将其重置为'.' // 然后进行下一个尝试 board[row][col] = '.'; } // 0~9均重复,输出false return false; } } } return true; } void solveSudoku(vector<vector<char> > &board) { internalSolveSudoku(board); } }; ~~~ 结果: ![](https://box.kancloud.cn/2016-01-05_568bb5eedbc8d.jpg) ## 四.小结 题目规定,输入保证是有效的,因此每填入一个数,无需检查整个矩阵是否合法,只需检查填入数当前行、列和`3*3`矩阵是否合法即可。