题目要求: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);
}
};

最新文章

  1. linux下centos的网络连接
  2. OC中property的有关属性
  3. Request header is too large
  4. EF架构~充血模型设置不被持久化的属性
  5. C#生成日期流水账号
  6. .NET开源工作流RoadFlow-流程设计-保存与发布
  7. (转)linux下jvm 参数调优
  8. 让Ecshop网店系统用户自动登陆
  9. Add controls dynamically in flowlayoutpanel
  10. Lorenzo Von Matterhorn
  11. jstree的简单用法
  12. Java 第一次作业
  13. java从pdf中提取文本
  14. A计划 HDU - 2102
  15. k8s环境搭建
  16. 下载安装mysql的一些坑
  17. scikit-FEM-例1-求解Possion边值问题
  18. HDU 4662 MU Puzzle 数论或者水题
  19. ComboBox智能搜索功能
  20. [javaEE] EL表达式调用java方法

热门文章

  1. Linux 网络编程的5种IO模型:阻塞IO与非阻塞IO
  2. Linux 网络编程的5种IO模型:信号驱动IO模型
  3. 【SpringBoot】07.SpringBoot文件上传
  4. python实现对于告警规则的判断思路
  5. Linux下Flask环境
  6. 第三方库文件Joi对数据进行验证的方法以及解决Joi.validate is not a function的问题
  7. Linux 笔记1
  8. Ceph数据盘怎样实现自动挂载
  9. 信息论-Turbo码学习
  10. Python博文_爬虫工程师是干什么的