Write a program to solve a Sudoku puzzle by filling the empty cells.
Empty cells is indicated by the character ‘.‘
.
Assume that there would be is only one unique solution.
A Sudoku Puzzle ...
... and its solution numbers marked in red.
The problem of solving Sudoku is the extension on the basis of the previous Valid Sudoku verification Sudoku, before that question let us verify whether the given array is a single array, which allows us to solve the Sudoku array, which is similar to the problem of having permutations all arranged, combinations combination items , N-queens n Queen problem and so on, especially with the N-queens n Queen problem solving ideas and similar, for each need to fill the number of the lattice into 1 to 9, each generation into a number to determine whether it is legal, if the legal will continue the next recursion, the end of the number back to '. ', When deciding whether a new number is valid, it is only necessary to determine whether the current number is valid, and it is not necessary to determine whether the array is a single array, because the previously added numbers are legal, which can make the program more efficient, as shown in the code:
classSolution { Public: voidSolvesudoku (vector<vector<Char> > &Board) { if(Board.empty () | | board.size ()! =9|| board[0].size ()! =9)return; Solvesudokudfs (board,0,0); } BOOLSolvesudokudfs (vector<vector<Char> > &board,intIintj) {if(i = =9)return true; if(J >=9)returnSolvesudokudfs (board, i +1,0); if(Board[i][j] = ='.') { for(intK =1; K <=9; ++k) {Board[i][j]= (Char) (k +'0'); if(isValid (board, I, J)) {if(Solvesudokudfs (board, I, J +1))return true; } Board[i][j]='.'; } } Else { returnSolvesudokudfs (Board, I, J +1); } return false; } BOOLIsValid (vector<vector<Char> > &board,intIintj) { for(intCol =0; Col <9; ++Col) { if(col! = J && board[i][j] = = Board[i][col])return false; } for(introw =0; Row <9; ++row) { if(Row! = i && board[i][j] = = Board[row][j])return false; } for(introw = I/3*3; Row < I/3*3+3; ++row) { for(intCol = j/3*3; Col < J/3*3+3; ++Col) { if(Row! = I | | Col! = j) && Board[i][j] = = Board[row][col])return false; } } return true; }};
[Leetcode] Sudoku Solver Solving Sudoku