<pre name="code" class="cpp">
<pre name="code" class="cpp">//25...9.4. //4.71.3..6 //8.34.759. //3.8.7..69 //.1.3.24.. //5.49.6.83 //9.6.3.7.8 //.3.6.8.1. //1.2.9.6.4
struct node { node(int r,int c):row(r),col(c) {} friend ostream& operator <<(ostream& os,node& a) { cout<<a.row<<" "<<a.col<<endl; return os; } int row,col; }; class Solution { vector<node>holes; bool rowFlg[9][10]; bool colFlg[9][10]; bool rectFlg[3][3][10]; public: bool isValidSudoku(vector<vector<char> > &board) { memset(rowFlg,0,sizeof(rowFlg)); memset(colFlg,0,sizeof(colFlg)); memset(rectFlg,0,sizeof(rectFlg)); holes.clear(); for(int i=0; i<board.size(); i++) { for(int j=0; j<board[i].size(); j++) { if(board[i][j]=='.')holes.push_back(node(i,j)); else { rowFlg[i][board[i][j]-'0']=true; colFlg[j][board[i][j]-'0']=true; rectFlg[i/3][j/3][board[i][j]-'0']=true; } } } return display(board,holes.size()-1); } bool display(vector<vector<char> > &board,int holeIndex) { if(holeIndex==-1)return true; for(int value=1; value<=9; value++) { if(checkCanDisplay(holes[holeIndex],value)) { //放置 node pos=holes[holeIndex]; board[pos.row][pos.col]=value+'0'; rowFlg[pos.row][value]=true; colFlg[pos.col][value]=true; rectFlg[pos.row/3][pos.col/3][value]=true; if(display(board,holeIndex-1))return true; rowFlg[pos.row][value]=false; colFlg[pos.col][value]=false; rectFlg[pos.row/3][pos.col/3][value]=false; } } return false; } bool checkCanDisplay(node pos,int value) { if(colFlg[pos.col][value]||rowFlg[pos.row][value]||rectFlg[pos.row/3][pos.col/3][value]) return false; return true; } };
数独解法
时间: 2024-10-17 00:48:27