1.题目
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...
求解数独。。。
2.思路
利用递归,先放一个数在格子上,如果合格,再放下一个格子,如果不合格,回溯。
class Solution {
public:
bool isValid(vector<vector<char>>& board,int position) { //测试当前position位置上的数是否合法
int row = position/9;
int col = position%9;
int gid = (row/3)*3 + col/3; //第(row/3*3 + col/3)个小方块的起始位置
for(int i=0;i<9;i++)
{
//check row
if(i != col && board[row][i] == board[row][col])
return false;
//check col
if(i != row && board[i][col] == board[row][col])
return false;
//check subgrid
int r = gid/3*3+i/3;
int c = gid%3*3+i%3;
if((r != row || c != col) && board[r][c] == board[row][col])
return false;
}
return true;
}
bool solve(vector<vector<char>>& board,int position){
if(position == 81)
return true;
int row = position/9;
int col = position%9;
if(board[row][col] == '.')
{
for(int k=1;k<=9;k++)
{
board[row][col] = k + '0';
if(isValid(board,position))
if(solve(board,position+1))
return true;
}
board[row][col] = '.';
return false;
}
else return solve(board,position+1);
}
void solveSudoku(vector<vector<char>>& board) {
solve(board,0);
}
};