题解 | #数独#
数独
http://www.nowcoder.com/practice/5e6c424b82224b85b64f28fd85761280
class Solution {
public:
vector<vector<char> > ans;
bool check(vector<vector<char> > &board,int row,int col,char val){
int startrow = row / 3 * 3,startcol = col / 3 * 3;
for(int i = startrow;i <= startrow + 2;++i)
for(int j = startcol;j <= startcol + 2;++j)
if(board[i][j] == val)
return false;
for(int i = 0;i < board.size();++i)
if(board[i][col] == val)
return false;
for(int i = 0;i < board[0].size();++i)
if(board[row][i] == val)
return false;
return true;
}
void back(vector<vector<char> > &board,int row,int col){
if(board[row][col] == '.'){
for(int i = 1;i <= 9;++i){
if(check(board,row,col,i + '0')){
board[row][col] = i + '0';
if(col + 1 < board[row].size())
back(board,row,col + 1);
else if(row + 1 < board.size())
back(board,row + 1,0);
else
ans = board;
board[row][col] = '.';
}
}
}
else{
if(col + 1 < board[row].size())
back(board,row,col + 1);
else if(row + 1 < board.size())
back(board,row + 1,0);
else
ans = board;
}
}
void solveSudoku(vector<vector<char> > &board) {
back(board,0,0);
board = ans;
}
};