# Sudoku Solver 数独

## 题目描述

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:
void solveSudoku(vector<vector<char> > &board) {
dfs(board, 0, 0);
}
bool dfs(vector<vector<char>> &board,int i,int j)
{
if (j >= 9) return dfs(board,i+1,0);//一行一行的遍历；
if (i == 9) return true;  //遍历结束
if (board[i][j] == '.') //此位置为空
{
for (int k = 1; k <= 9; k++)
{
board[i][j] = char(k + '0'); //依次填入1-9，判断是否合格；
if (isValid(board, i, j))
{
if (dfs(board, i, j + 1)) return true;
}
board[i][j] = '.'; //如果不合格，重新设为空，填入下一个数字；
}
}
else
return dfs(board,i,j+1); //如果不为空，递归下一列；
return false;
}
bool isValid(vector<vector<char>> &board,int i,int j)
{
for (int k = 0; k < 9; k++)  //遍历每一列，判断有重复
{
if (k != j&&board[i][j] == board[i][k]) return false;
}
for (int k = 0; k < 9; k++)  //遍历每一行，判断有重复
{
if (k != i&&board[i][j] == board[k][j]) return false;
}
for (int row = i / 3 * 3; row < i / 3 * 3 + 3; row++)//遍历(i,j)所在的小九宫格，判断有重复
{
for (int col = j / 3 * 3; col < j / 3 * 3 + 3; col++)
{
if ((row != i || col != j) && board[i][j] == board[row][col])
return false;
}
}
return true;
}
};