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.
A Sudoku Puzzle ...
... and its solution numbers marked in red.
Using backtracking, recursive implementations continue to judge the next element if the current element satisfies the Sudoku condition. If the current element does not satisfy the Sudoku condition, then returns, recursively backtracking to the previous element to continue the lookup because there is definitely a solution, so in the judgment of the time can not use the hash table, directly determine the other position of the elements and the current to determine whether the element is equal to it.
1 classSolution {2 Public:3 4 BOOLIsValid (vector<vector<Char> > &board,intI0,intj0)5 {6 Chartarget=Board[i0][j0];7 8 for(intI=0;i<9; i++)9 {Ten if(I==I0)Continue; One if(board[i][j0]==target) A { - return false; - } the } - - - for(intj=0;j<9; j + +) + { - if(j==j0)Continue; + if(board[i0][j]==target) A { at return false; - } - } - - for(inti=i0/3*3; i<i0/3*3+3; i++) - { in - for(intj=j0/3*3; j<j0/3*3+3; j + +) to { + if(i==i0&&j==j0)Continue; - if(board[i][j]==target) the { * return false; $ }Panax Notoginseng } - } the + return true; A } the + - BOOLScanpos (vector<vector<Char> > &board,intPOS) $ { $ if(pos==Bayi)return true; - - the BOOLflag=false; - inti0=pos/9;Wuyi intj0=pos%9; the - if(board[i0][j0]!='.') Wu { - returnScanpos (board,pos+1); About } $ - for(intj=1; j<=9; j + +) - { - Aboard[i0][j0]='0'+J; + if(IsValid (board,i0,j0)) the { - if(Scanpos (board,pos+1)) $ { theflag=true; the Break; the } the } - } in the if(flag==false) the { Aboutboard[i0][j0]='.'; the return false; the } the Else + { - return true; the }Bayi } the the - voidSolvesudoku (vector<vector<Char> > &Board) { -Scanpos (board,0); the } the};
"Leetcode" Sudoku Solver