Sudoku Solver Total accepted:11799 Total submissions:56732 My submissions
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.
question: Fill in the sudoku and return whether the data is filled successfully
train of thought: DFS
find a position that has not been filled, and enter a number in the 0-9 format, determine whether or not.
if it is reasonable, it can be transferred to a similar problem, so it can be implemented recursively.
bool solvesudoku (vector & board)
whether the result is successfully filled with the sudoku whose current status is Board
Bool isvalid (const vector <char> & board, int X, int y) {// check the row for (Int J = 0; j <9; ++ J) if (J! = Y & Board [x] [J] = Board [x] [Y]) return false; // check the column for (INT I = 0; I <9; ++ I) if (I! = X & Board [I] [Y] = Board [x] [Y]) return false; // check the small block for (INT I = 0; I <3; ++ I) for (Int J = 0; j <3; ++ J) {If (! (X/3*3 + I = x & Y/3*3 + J = y) & Board [X/3*3 + I] [Y/3*3 + J] = Board [x] [Y]) return false;} return true ;} bool solvesudoku (vector <char> & board) {for (INT I = 0; I <9; ++ I) {for (Int J = 0; j <9; ++ J) {If (Board [I] [J] = '. ') {for (int K = 0; k <9; ++ K) {board [I] [J] = K + '1'; If (isvalid (board, i, j) & solvesudoku (board) return true; Board [I] [J] = '. ';} return false ;}}} return true; // This sentence is missing and Wa has been written many times}
Leetcode DFS Sudoku Solver