Question:
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.
A Sudoku puzzle...
... And its solution numbers marked in red.
This question is more difficult than determining whether the question value is valid.
There are many solutions on the Internet, and some are complicated and concise. The records I understand are as follows:
The idea should be clear. Use backtracking. Here we use Recursive Backtracking. I specially reviewed the Backtracking Method. Is to use DFS. Traverse all the time to find the correct solution. In this process, the corresponding pruning is implemented through the isvalid below. Note that annotations are provided. A thousand words is not as good as a line of code.
Class solution {PRIVATE: bool isvalid (vector <char> & board, int X, int y) {for (INT I = 0; I <9; ++ I) // determine whether the row contains repeated characters {If (Board [I] [Y] = Board [x] [Y] & I! = X) return false;} For (INT I = 0; I <9; ++ I) // column {If (Board [x] [I] = Board [x] [Y] & I! = Y) return false;} For (INT I = 3 * (X/3); I <3 * (X/3) + 3; ++ I) // check whether the child palace has repeated for (Int J = 3 * (y/3); j <3 * (y/3) + 3; ++ J) // draw a box on the paper to display the relationship between the start and end points of each grid and XY. {If (Board [I] [J] = Board [x] [Y] & & I! = X & J! = Y) return false;} return true; // if none of them are returned, the return value is legal.} public: bool solvesudoku (vector <char> & Board) {// backtracking for (INT I = 0; I <9; ++ I) for (Int J = 0; j <9; ++ J) {If ('. '= Board [I] [J]) {for (int K = 1; k <= 9; ++ K) // note that it is between 1 and 9, do not mistakenly think that 0 to 8 {board [I] [J] = '0' + k; // = do not write =. After debugging for 10 minutes, I found that I wrote =, tear collapse if (isvalid (board, I, j) & solvesudoku (board) // if the number of added values is valid and there is a solution after addition, True returns true; board [I] [J] = '. '; // If no result is returned, the K value is invalid. Therefore, you must restore the element '. '} return false ;}} return true; // The number is filled in for the last time. If the solution is successful, the returned result is correct }};
Leetcode 36th -- Sudoku Solver