Problem:
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 93x3
sub-boxes of the grid.
Empty cells are indicated by the character '.'
.
A sudoku puzzle...
...and its solution numbers marked in red.
Note:
- 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
.
思路:
采用递归的思想。基本的思路是按照从上到下,从左到右的顺序,在所有的空格处依次填入1-9的数字,然后判断填进去之后是否满足数独的要求,如果满足则继续填下一个空格,不满足则在当前空格处填入下一个数字。在填的时候利用了递归的思想,如果checkSudoku(board, i, j, c),则说明数独有效,再进行solveSudoku(board, i, j+1)操作。
值得注意的是,虽然题目的函数返回值为空,但事实上的输出为board,所以我们在传递参数的时候传递的是board的引用&board,如果不传递引用则board不会被改变。
Solution (C++):
public:
void solveSudoku(vector<vector<char>>& board) {
solveSudoku(board, 0, 0);
}
private:
bool checkSudoku(vector<vector<char>> &board, int i, int j, char val) { //检查填入val后数独是否有效
int row = i - i%3, column = j - j%3;
for (int x = 0; x < 9; x++) {
if (board[i][x] == val) return false;
if (board[x][j] == val) return false;
if (board[row+x/3][column+x%3] == val) return false;
}
return true;
}
bool solveSudoku(vector<vector<char>> &board, int i, int j) {
if (i == 9) return true; //说明数独填完
if (j == 9) return solveSudoku(board, i+1, 0); //说明第i行填完,开始填第i+1行
if (board[i][j] != '.') return solveSudoku(board, i, j+1);
for (char c = '1'; c <= '9'; c++) {
if (checkSudoku(board, i, j, c)) {
board[i][j] = c;
if (solveSudoku(board, i, j+1)) return true;
board[i][j] = '.';
}
}
return false;
}
性能:
Runtime: 16 ms Memory Usage: 8.9 MB