Sudoku Solver
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...
很好的例子理解递归,回朔,以及循环中的递归。
1 class Solution { 2 public: 3 void solveSudoku(vector<vector<char> > &board) { 4 process(board, 0,0); 5 6 } 7 bool process(vector<vector<char>> &board,int i,int j) 8 { 9 10 if(j==9) 11 { 12 return process(board,i+1,0);//!!! 13 } 14 if(i==9) 15 { 16 //cout<<"true"; 17 return true; 18 } 19 if(board[i][j]=='.') 20 { 21 for(int k=1;k<10;k++) 22 { 23 24 if(isValid(board,i,j,k)) 25 { 26 board[i][j]='0'+k; 27 if(process(board,i,j+1)) {return true;} 28 board[i][j]='.'; 29 } 30 31 } 32 33 return false; 34 } 35 else return process(board,i,j+1); 36 37 } 38 bool isValid(vector<vector<char>> &board,int i, int j, int k) 39 { 40 41 char qq='0'+k; 42 for(int m=0;m<9;m++) 43 { 44 if(board[i][m]==qq){return false;} 45 } 46 for(int m=0;m<9;m++) 47 { 48 if(board[m][j]==qq)return false; 49 } 50 int m=i/3, n=j/3; 51 for(int p=m*3;p<m*3+3;p++) 52 { 53 for(int q=n*3;q<n*3+3;q++) 54 { 55 if(board[p][q]==qq)return false; 56 } 57 } 58 return true; 59 } 60 };