Title Link: Sudoku Solver
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.
The requirement of this problem is to fill Sudoku, where empty position with '. ' Filled, with a unique solution.
This is a valid Sudoku version of the problem, the same place is the use of 3 arrays can be used to record each row, each column, each nine the number of cells appear. To fill sucks, is to fill each vacancy 1~9, to see whether the solution. This is a backtracking problem that can be resolved by recursion.
Before recursive backtracking, use the array place to record the empty position in the Sudoku, using Used1, Used2, and used3 to mark each row, each column, the number of each nine lattice, and then go through the Sudoku, initialize the settings. Then, the recursion is processed retrospectively, and each time it is filled with 1~9 to see if it can be filled in. If you can, recursively go to the next position; otherwise, try filling in the next number.
Time complexity: O (???)
Space complexity: O (n2)
1 class Solution2 {3 int used1[9][9], Used2[9][9], used3[9][9];4 5 Public:6 void Solvesudoku(Vector<Vector<Char> > &Board)7 {8 Vector<Vector<int>> Place;9 for(int I = 0; I < Board.size(); ++ I)Ten for(int J = 0; J < Board[I].size(); ++ J) One { A if(Board[I][J] == '. ') - Place.push_back({I, J}); - Else the { - int Num = Board[I][J] - ' 0 ' - 1, k = I / 3 * 3 + J / 3; - used1[I][Num] = Used2[J][Num] = used3[k][Num] = 1; - } + } - + DFS(Board, Place, Place.size() - 1); A } at - Private: - BOOL DFS(Vector<Vector<Char>> &Board, Vector<Vector<int>> & Place, int N) - { - if(N < 0) - return true; in - int I = Place[N][0], J = Place[N][1]; to + for(int Num = 0; Num < 9; ++ Num) - { the int k = I / 3 * 3 + J / 3; * if(!used1[I][Num] && !Used2[J][Num] && !used3[k][Num]) $ {Panax Notoginseng used1[I][Num] = Used2[J][Num] = used3[k][Num] = 1; - Board[I][J] = Num + ' 0 ' + 1; the + if(DFS(Board, Place, N - 1)) A return true; the + used1[I][Num] = Used2[J][Num] = used3[k][Num] = 0; - Board[I][J] = '. '; $ } $ } - - return false; the } - };
Reprint please indicate source: Leetcode---37. Sudoku Solver
Leetcode---37. Sudoku Solver