题目描述:
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.
② Its solution numbers marked in red.
分析:
题意:给定数独游戏当前一个局面('.'表示空格,未填写),返回所有空格填写完成的局面。假设只存在唯一解。
思路:此题是LeetCode 36的进化版本。因为要求填写所有空格,因此采用DFS搜索。对于每一个空格,尝试1→9个数字,每一个数字都需要对每行、每列、每个小矩阵三条规则进行判断(若存在重复数字,表明当前填写数字不符合)。① 若当前空格填写完成、从当前局面继续搜索完成所有填写,则返回true表示完成;② 若当前空格尝试9个数字均返回false,表示无法完成,需要返回之前的搜索局面、重新搜索。③ 完成所有空格填写之后,返回true表示完成。
代码:
#include <bits/stdc++.h>
using namespace std;
// DFS
class Solution {
private:
bool check(vector<vector<char>>& board, int x, int y, char c){
// rows ans columns
for(int i = 0; i <= 8; i++){
if(board[x][i] == c){
return false;
}
if(board[i][y] == c){
return false;
}
}
// cubes
int xx = (x / 3) * 3, yy = (y / 3) * 3;
for(int i = 0; i <= 2; i++){
for(int j = 0; j <= 2; j++){
if(board[xx + i][yy + j] == c){
return false;
}
}
}
return true;
}
bool DFS(vector<vector<char>>& board){
for(int i = 0; i <= 8; i++){
for(int j = 0; j <= 8; j++){
if(board[i][j] == '.'){
for(int k = 1; k <= 9; k++){
if(check(board, i, j, k + '0')){
board[i][j] = k + '0';
if(DFS(board)){
return true;
}
else{
board[i][j] = '.';
}
}
}
return false;
}
}
}
return true;
}
public:
void solveSudoku(vector<vector<char>>& board) {
DFS(board);
}
};