leetcode笔记:Sudoku Solver
2015-10-06 20:01
477 查看
一.题目描述
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.
The following photo is a sudoku puzzle…
…and its solution numbers marked in red:
二.题目分析
注意题目说明了输入保证有且只有一个解,所以试探每一个格子的时候,只需要考虑当前行、列、矩形框满足条件,满足就进入下一个格子试探,不满足回溯。
首先,编写一个函数
于是,对于矩阵中的每个空位
只有正确达到矩阵最右下角位置才算填充成功,此时返回填充结果。
关于回朔算法,以下博客写得浅显易懂,可以参考参考:
http://www.cnblogs.com/steven_oyj/archive/2010/05/22/1741376.html
http://www.cnblogs.com/Creator/archive/2011/05/20/2052341.html
三.示例代码
结果:
四.小结
题目规定,输入保证是有效的,因此每填入一个数,无需检查整个矩阵是否合法,只需检查填入数当前行、列和
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.
The following photo is a sudoku puzzle…
…and its solution numbers marked in red:
二.题目分析
注意题目说明了输入保证有且只有一个解,所以试探每一个格子的时候,只需要考虑当前行、列、矩形框满足条件,满足就进入下一个格子试探,不满足回溯。
首先,编写一个函数
isValidSudoku()用于测试矩阵当前坐标的值是否合法,检查当前值在行、列以及
3*3的矩阵内是否有效。
于是,对于矩阵中的每个空位
'.',尝试填入
1~9并检查是否合法,正确则往下一个位置递归。
只有正确达到矩阵最右下角位置才算填充成功,此时返回填充结果。
关于回朔算法,以下博客写得浅显易懂,可以参考参考:
http://www.cnblogs.com/steven_oyj/archive/2010/05/22/1741376.html
http://www.cnblogs.com/Creator/archive/2011/05/20/2052341.html
三.示例代码
#include <iostream> #include <vector> using namespace std; class Solution { public: bool isValidSudoku(vector<vector<char> > &board, int x, int y) { // 同一列中是否出现相同的数 for (int row = 0; row < 9; ++row) if ((x != row) && (board[row][y] == board[x][y])) return false; // 同一行中是否出现相同的数 for (int col = 0; col < 9; ++col) if ((y != col) && (board[x][col] == board[x][y])) return false; // 3 * 3方格中是否出现相同的数 for (int row = (x / 3) * 3; row < (x / 3 + 1) * 3; ++row) for (int col = (y / 3) * 3; col < (y / 3 + 1) * 3; ++col) if ((x != row) && (y != col) && (board[row][col] == board[x][y])) return false; // 满足条件,则返回true 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] = '.'; } // 0~9均重复,输出false return false; } } } return true; } void solveSudoku(vector<vector<char> > &board) { internalSolveSudoku(board); } };
结果:
四.小结
题目规定,输入保证是有效的,因此每填入一个数,无需检查整个矩阵是否合法,只需检查填入数当前行、列和
3*3矩阵是否合法即可。
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- 关于指针的一些事情
- c++ primer 第五版 笔记前言
- share_ptr的几个注意点
- Lua中调用C++函数示例
- Lua教程(一):在C++中嵌入Lua脚本
- Lua教程(二):C++和Lua相互传递数据示例
- C++联合体转换成C#结构的实现方法
- C++编写简单的打靶游戏
- C++ 自定义控件的移植问题
- C++变位词问题分析
- C/C++数据对齐详细解析
- C++基于栈实现铁轨问题
- C++中引用的使用总结
- 使用Lua来扩展C++程序的方法
- C++中调用Lua函数实例
- Lua和C++的通信流程代码实例
- C与C++之间相互调用实例方法讲解
- 解析C++中派生的概念以及派生类成员的访问属性
- C++ Custom Control控件向父窗体发送对应的消息