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.
solution:用dfs来做,统计所有的为空的格子,然后依次访问每个格子,对该格子填1-9,判断成立则访问递归调用访问下一个格子,否则置回.值,继续填下一个数。结束条件是访问到最后一个格子,即cur == len -1
此处用dots数组记录空格子的索引,将二维数组索引视为一维进行添加。
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<int>dots;
for(int row = 0; row < 9; row++)
{
for(int col = 0; col < 9; col++)
{
if(board[row][col] == '.')
{
int temp = row * 9 + col;
dots.push_back(temp);
}
}
}
int len = dots.size();
sudokuSolver(dots, 0, len, board);
}
bool sudokuSolver(vector<int>dots, int cur, int len, vector<vector<char> > &board)
{
if(cur == len) return true;
int num = dots[cur];
int row = num / 9;
int col = num % 9;
for(int nu = 0; nu < 9; nu++)
{
if( isValid(nu, row, col, board) )
{
char res = (char)('1' + nu);
board[row][col] = res;
if( sudokuSolver(dots, cur+1, len, board) )
return true;
board[row][col] = '.';
}
}
return false;
}
bool isValid(int nu, int row, int col, vector<vector<char> > &board)
{
for( int i = 0; i < 9; i++ )
{
int rowVal = board[ row][ i ] - '1';
int colVal = board[ i ][ col ] - '1';
int blockVal = board[ row - row%3 + i/3 ][ col - col%3 + i%3 ] - '1';
if(rowVal == nu || colVal == nu || blockVal == nu)
return false;
}
return true;
}
};