Leetcode Note: Sudoku Solver
I. Description
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...
... And its solution numbers marked in red: <喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> VcD4NCjxwPjxpbWcgYWx0PQ = "here write picture description" src = "http://www.bkjia.com/uploads/allimg/151012/06011140G-1.png" title = "\"/>
Ii. Question Analysis
Note that there is only one solution for the input, so when testing each grid, you only need to consider that the current row, column, and rectangle meet the conditions, and then enter the next grid to test, does not support backtracking.
First, write a functionisValidSudoku()
Used to test whether the value of the current coordinate of the matrix is legal, check the current value in rows, columns, and3*3
Is it valid in the matrix.
Therefore, for each blank space in the Matrix'.'
, Try to fill in1~9
And check whether it is valid. If it is correct, it is recursive to the next position.
The filling is successful only when the position at the bottom right corner of the matrix is reached. The filling result is returned.
AboutReturn AlgorithmThe following blogs are easy to understand. For more information, see:
Http://www.cnblogs.com/steven_oyj/archive/2010/05/22/1741376.html
Http://www.cnblogs.com/Creator/archive/2011/05/20/2052341.html
Iii. Sample Code
# Include
# Include
Using namespace std; class Solution {public: bool isValidSudoku (vector
> & Board, int x, int y) {// whether the same number exists in the same column for (int row = 0; row <9; ++ row) if (x! = Row) & (board [row] [y] = board [x] [y]) return false; // whether the same number of for (int col = 0; col <9; ++ col) if (y! = Col) & (board [x] [col] = board [x] [y]) return false; // check whether the same number appears in the 3*3 square 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; // if conditions are met, true return true ;} bool internalSolveSudoku (vector
> & 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; // if the number of current cells is incorrect, reset it '. '// then proceed to the next attempt board [row] [col] = '. ';} // 0 ~ 9 are repeated, and the output is false return false; }}return true;} void solveSudoku (vector
> & Board) {internalSolveSudoku (board );}};
Result:
Iv. Summary
The input guarantee is valid. Therefore, you do not need to check whether the entire matrix is valid for each input number. You only need to check whether the current row, column, and3*3
Check whether the matrix is valid.