[LeetCode] 112: Sudoku Solver

本文提供了一种使用深度优先搜索(DFS)算法解决数独问题的方法。通过预先填充已知数字并标记未解决的单元格,该算法能够递归地尝试每一个可能的数字直到找到解决方案。实现中还考虑了数独的唯一解假设。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

[Problem]

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.

[LeetCode] 112: Sudoku Solver - coder007 - Coder007的博客

A sudoku puzzle...

[LeetCode] 112: Sudoku Solver - coder007 - Coder007的博客

...and its solution numbers marked in red.


[Solution]

class Solution {
public:
/**
* DFS
*/
bool DFS(vector<vector<char> > &board, vector<pair<int, int> > unSolve, bool rowUsed[9][10], bool columnUsed[9][10], bool cubeUsed[9][10]){
if(unSolve.size() == 0)return true;

// the last one
if(unSolve.size() == 1){
int i = unSolve[0].first;
int j = unSolve[0].second;

// get the unused number in the row i
int k = 1;
for(k = 1; k <= 9; ++k){
if(!rowUsed[i][k])break;
}

// there is no unused number in the row i, or the number is used in the column j or the cube (i/3)*3+j/3
if(k == 10 || columnUsed[j][k] || cubeUsed[(i/3)*3+j/3][k])return false;

// success
board[i][j] = k + '0';
return true;
}
else{
int i = unSolve[0].first;
int j = unSolve[0].second;

// get the unused number in the row i
for(int k = 1; k <= 9; ++k){
// both the row i, the column j and the cube (i/3)*3+j/3 not use k
if(rowUsed[i][k] || columnUsed[j][k] || cubeUsed[(i/3)*3+j/3][k])continue;

// set the used
rowUsed[i][k] = columnUsed[j][k] = cubeUsed[(i/3)*3+j/3][k] = true;

// set the board
board[i][j] = k + '0';

// remove a pair from unSolve
unSolve.erase(unSolve.begin());

// solved
if(DFS(board, unSolve, rowUsed, columnUsed, cubeUsed)){
return true;
}

// unsolved, reset the marks
rowUsed[i][k] = columnUsed[j][k] = cubeUsed[(i/3)*3+j/3][k] = false;
board[i][j] = '.';
unSolve.insert(unSolve.begin(), pair<int, int>(i, j));
}
}
return false;
}
/**
* solve Sudoku
*/
void solveSudoku(vector<vector<char> > &board) {
// Note: The Solution object is instantiated only once and is reused by each test case.
// initial
vector<pair<int, int> > unSolve;
bool rowUsed[9][10], columnUsed[9][10], cubeUsed[9][10]; // 9 rows, 9 columns, 9 cubes
memset(rowUsed, 0, sizeof(rowUsed));
memset(columnUsed, 0, sizeof(columnUsed));
memset(cubeUsed, 0, sizeof(cubeUsed));
for(int i = 0; i < 9; ++i){
for(int j = 0; j < 9; ++j){
if(board[i][j] != '.'){
rowUsed[i][board[i][j]-'0'] = true;
columnUsed[j][board[i][j]-'0'] = true;
cubeUsed[(i/3)*3+j/3][board[i][j]-'0'] = true;
}
else{
unSolve.push_back(pair<int, int>(i, j));
}
}
}

// DFS
DFS(board, unSolve, rowUsed, columnUsed, cubeUsed);
}
};

说明:版权所有,转载请注明出处。 Coder007的博客
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值