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...
...and its solution numbers marked in red.
简单的回溯搜索即可
class Solution { public: void solveSudoku(vector<vector<char> > &board) { // Note: The Solution object is instantiated only once and is reused by each test case. vector<vector<bool> >check; vector<bool> one; one.resize(9,false); check.resize(27,one); vector<vector<int> > empty; for(int i=0;i<9;i++){ for(int j=0;j<9;j++){ int val=board[i][j]-'1'; if(val>=0&&val<9){ check[i][val]=true; check[9+j][val]=true; check[18+(i/3)*3+j/3][val]=true; } else{ int size=empty.size(); empty.resize(size+1); empty[size].push_back(i); empty[size].push_back(j); empty[size].push_back(0); } } } int index=0; while(true){ int val=empty[index][2]; int i=empty[index][0]; int j=empty[index][1]; if(val==9){ //go back index--; val=empty[index][2]; i=empty[index][0]; j=empty[index][1]; check[i][val]=false; check[9+j][val]=false; check[18+(i/3)*3+j/3][val]=false; empty[index][2]++; } else{ if(check[i][val]||check[9+j][val]||check[18+(i/3)*3+j/3][val]){ //try next val empty[index][2]++; } else{ check[i][val]=true; check[9+j][val]=true; check[18+(i/3)*3+j/3][val]=true; index++; if(index==empty.size()){ //end for(int k=0;k<empty.size();k++){ board[empty[k][0]][empty[k][1]]='1'+empty[k][2]; } return; } empty[index][2]=0; } } } } };