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
1:採用遞歸;2:檢測當前空cell中放置的字符是不是滿足題意,如果不滿足,放置其它字符或者回朔;
bool isValidSudokuCore(vector<vector<char> > &board, int curX, int curY)
{
for(int i = 0; i < (int)board.size(); i++)
{
if(i != curX && board[i][curY] !='.' && board[i][curY] == board[curX][curY])
{
return false;
}
}
for(int i = 0; i < (int)board[0].size(); i++)
{
if(i != curY && board[curX][i] != '.' && board[curX][i] == board[curX][curY])
{
return false;
}
}
int rows = curX / 3;
int columns = curY / 3;
for(int i = 0; i < 3; i++)
{
for(int j = 0; j < 3; j++)
{
if((rows * 3 + i != curX || columns * 3 + j != curY) && board[rows * 3 + i][columns * 3 + j] != '.' && board[rows * 3 + i][columns * 3 + j] == board[curX][curY])
{
return false;
}
}
}
return true;
}
void solveSudoku(vector<vector<char> > &board)
{
solveSudokuCore(board);
}
bool solveSudokuCore(vector<vector<char> > &board)
{
for(int i = 0; i < 9; i++)
{
for(int j = 0; j < 9; j++)
{
if(board[i][j] == '.')
{
bool flag = false;
for(int k = 1; k <= 9; k++)
{
board[i][j] = k + '0';
flag = isValidSudokuCore(board, i, j) && solveSudokuCore(board);
if(flag)
{
return true;
}
}
if(flag == false)
{
board[i][j] = '.';
return false;
}
}
}
}
return true;
}