题目描述(Hard)
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
.
题目链接
https://leetcode.com/problems/sudoku-solver/description/
算法分析
深搜,对每个位置判断,时间复杂度,可与【LeetCode】14.Valid Sudoku一起食用。
提交代码:
class Solution {
public:
void solveSudoku(vector<vector<char>>& board) {
DFSsolveSudoku(board);
}
private:
bool DFSsolveSudoku(vector<vector<char>>& board) {
for (int i = 0; i < 9; ++i) {
for (int j = 0; j < 9; ++j) {
if (board[i][j] == '.') {
for (int num = 0; num < 9; ++num) {
board[i][j] = '1' + num;
if (isValid(board, i, j) && DFSsolveSudoku(board))
return true;
board[i][j] = '.';
}
return false;
}
}
}
return true;
}
bool isValid(vector<vector<char>>& board, int x, int y) {
// 所在列有效性检测
for (int i = 0; i < 9; ++i) {
if (i != x && board[i][y] == board[x][y])
return false;
}
// 所在行有效性检测
for (int j = 0; j < 9; ++j) {
if (j != y && board[x][j] == board[x][y])
return false;
}
// 所在子格有效性检测
for (int i = 3* (x / 3); i < 3* (x / 3 + 1); ++i)
for (int 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;
}
};