题目:
Write a program to solve a Sudoku puzzle by filling the empty cells.
A sudoku solution must satisfy all of the following rules:
Each of the digits 1-9 must occur exactly once in each row.
Each of the digits 1-9 must occur exactly once in each column.
Each of the the digits 1-9 must occur exactly once in each of the 9 3x3 sub-boxes of the grid.
Empty cells are indicated by the character ‘.’
The given board contain only digits 1-9 and the character ‘.’.
You may assume that the given Sudoku puzzle will have a single unique solution.
The given board size is always 9x9.
简单的数独填写
很明显可以得出该题采用dfs加上回溯法,改写之前写过的八皇后就完事儿了。
代码如下:
class Solution
{
public:
bool isValid(vector<vector<char> > &board, int x, int y) //判断现有棋盘状态是否合法
{
int i, j;
for (i = 0; i < 9; i++)
if (i != x && board[i][y] == board[x][y]) // 横向
return false;
for (j = 0; j < 9; j++)
if (j != y && board[x][j] == board[x][y]) // 纵向
return false;
for (i = 3 * (x / 3); i < 3 * (x / 3 + 1); i++) //每一个九宫格
for (j = 3 * (y / 3); j < 3 * (y / 3 + 1); j++)
if (i != x && j != y && board[i][j] == board[x][y])
return false;
return true;
}
bool solveSudoku(vector<vector<char> > &board)
{
for (int i = 0; i < 9; ++i)
for (int j = 0; j < 9; ++j)
{
if ('.' == board[i][j]) // 如果为空
{
for (int k = 1; k <= 9; ++k) //尝试性填入1~9
{
board[i][j] = '0' + k;
if (isValid(board, i, j) && solveSudoku(board)) // 如果合法,返回true
return true;
board[i][j] = '.'; // 之前的填法都不合法,回溯的将之前填过的空置空5
}
return false; // 如果1~9都没有解出来,返回错误。
}
}
return true;
}
};