LeetCode 037 Sudoku Solver
2024-09-02 06:13:53
题目要求:Sudoku Solver
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...
...and its solution numbers marked in red.
分析:
参考网址:http://www.cnblogs.com/panda_lin/archive/2013/11/04/sudoku_solver.html
回溯法尝试所有解0_o
① 对于每个空位'.',遍历1~9,check合理之后递归;
② check的时候,不用遍历整个数独,只需检查加入的行、列和块就足够了。
代码如下:
class Solution {
public:
bool isValidSudoku(vector<vector<char> > &board, int x, int y) {
int row, col; // Same value in the same column?
for (row = 0; row < 9; ++row) {
if ((x != row) && (board[row][y] == board[x][y])) {
return false;
}
} // Same value in the same row?
for (col = 0; col < 9; ++col) {
if ((y != col) && (board[x][col] == board[x][y])) {
return false;
}
} // Same value in the 3 * 3 block it belong to?
for (row = (x / 3) * 3; row < (x / 3 + 1) * 3; ++row) {
for (col = (y / 3) * 3; col < (y / 3 + 1) * 3; ++col) {
if ((x != row) && (y != col) && (board[row][col] == board[x][y])) {
return false;
}
}
} return true;
} bool internalSolveSudoku(vector<vector<char> > &board) {
for (int row = 0; row < 9; ++row) {
for (int col = 0; col < 9; ++col) {
if ('.' == board[row][col]) {
for (int i = 1; i <= 9; ++i) {
board[row][col] = '0' + i; if (isValidSudoku(board, row, col)) {
if (internalSolveSudoku(board)) {
return true;
}
} board[row][col] = '.';
} return false;
}
}
} return true;
} void solveSudoku(vector<vector<char> > &board) {
internalSolveSudoku(board);
}
};
最新文章
- linux下centos的网络连接
- OC中property的有关属性
- Request header is too large
- EF架构~充血模型设置不被持久化的属性
- C#生成日期流水账号
- .NET开源工作流RoadFlow-流程设计-保存与发布
- (转)linux下jvm 参数调优
- 让Ecshop网店系统用户自动登陆
- Add controls dynamically in flowlayoutpanel
- Lorenzo Von Matterhorn
- jstree的简单用法
- Java 第一次作业
- java从pdf中提取文本
- A计划 HDU - 2102
- k8s环境搭建
- 下载安装mysql的一些坑
- scikit-FEM-例1-求解Possion边值问题
- HDU 4662 MU Puzzle 数论或者水题
- ComboBox智能搜索功能
- [javaEE] EL表达式调用java方法