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:
char row[9][9];
char column[9][9];
char block[9][9];
void solveSudoku(vector<vector<char> > &board) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
makeMatrix(board);
int flag = 0;
solve(board,0,0,flag);
}
void solve(vector<vector<char>>& board,int i,int j,int& flag)
{
if(board[i][j] == '.'){
for(char k = '1';k<='9';k++)
{
int digit = k-'1';
if(row[i][digit] != 0) continue;
if(column[j][digit] != 0) continue;
if(block[i/3 * 3 + j/3][digit] != 0) continue;
row[i][digit] = 1;
column[j][digit] = 1;
block[i/3 * 3 + j/3][digit] = 1;
board[i][j] = k;
if(j < 8) solve(board,i,j+1,flag);
else if(i < 8) solve(board,i+1,0,flag);
else flag = 1;
if(flag == 1) return;
board[i][j] = '.';
row[i][digit] = 0;
column[j][digit] = 0;
block[i/3 * 3 + j/3][digit] = 0;
}
}else{
if(j < 8) solve(board,i,j+1,flag);
else if(i < 8) solve(board,i+1,0,flag);
else flag = 1;
if(flag == 1) return;
}
}
void makeMatrix(vector<vector<char> > &board) {
// Start typing your C/C++ solution berlow
// DO NOT write int main() function
memset(row,0,81);
memset(column,0,81);
memset(block,0,81);
for(int i = 0;i<9;i++)
{
for(int j = 0;j<9;j++)
{
if(board[i][j] == '.') continue;
int digit = board[i][j]-'1';
row[i][digit] = 1;
column[j][digit] = 1;
block[i/3 * 3 + j/3][digit] = 1;
}
}
}
};
20 milli secs.