## 一.题目描述
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…
![](https://box.kancloud.cn/2016-01-05_568bb5ee977fb.jpg)
…and its solution numbers marked in red:
![](https://box.kancloud.cn/2016-01-05_568bb5eea7cee.jpg)
## 二.题目分析
注意题目说明了输入保证有且只有一个解,所以试探每一个格子的时候,只需要考虑当前行、列、矩形框满足条件,满足就进入下一个格子试探,不满足回溯。
首先,编写一个函数`isValidSudoku()`用于测试矩阵当前坐标的值是否合法,检查当前值在行、列以及`3*3`的矩阵内是否有效。
于是,对于矩阵中的每个空位`'.'`,尝试填入`1~9` 并检查是否合法,正确则往下一个位置递归。
只有正确达到矩阵最右下角位置才算填充成功,此时返回填充结果。
关于**回朔算法**,以下博客写得浅显易懂,可以参考参考:
[http://www.cnblogs.com/steven_oyj/archive/2010/05/22/1741376.html](http://www.cnblogs.com/steven_oyj/archive/2010/05/22/1741376.html)
[http://www.cnblogs.com/Creator/archive/2011/05/20/2052341.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);
}
};
~~~
结果:
![](https://box.kancloud.cn/2016-01-05_568bb5eedbc8d.jpg)
## 四.小结
题目规定,输入保证是有效的,因此每填入一个数,无需检查整个矩阵是否合法,只需检查填入数当前行、列和`3*3`矩阵是否合法即可。
- 前言
- 2Sum
- 3Sum
- 4Sum
- 3Sum Closest
- Remove Duplicates from Sorted Array
- Remove Duplicates from Sorted Array II
- Search in Rotated Sorted Array
- Remove Element
- Merge Sorted Array
- Add Binary
- Valid Palindrome
- Permutation Sequence
- Single Number
- Single Number II
- Gray Code(2016腾讯软件开发笔试题)
- Valid Sudoku
- Rotate Image
- Power of two
- Plus One
- Gas Station
- Set Matrix Zeroes
- Count and Say
- Climbing Stairs(斐波那契数列问题)
- Remove Nth Node From End of List
- Linked List Cycle
- Linked List Cycle 2
- Integer to Roman
- Roman to Integer
- Valid Parentheses
- Reorder List
- Path Sum
- Simplify Path
- Trapping Rain Water
- Path Sum II
- Factorial Trailing Zeroes
- Sudoku Solver
- Isomorphic Strings
- String to Integer (atoi)
- Largest Rectangle in Histogram
- Binary Tree Preorder Traversal
- Evaluate Reverse Polish Notation(逆波兰式的计算)
- Maximum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Longest Common Prefix
- Recover Binary Search Tree
- Binary Tree Level Order Traversal
- Binary Tree Level Order Traversal II
- Binary Tree Zigzag Level Order Traversal
- Sum Root to Leaf Numbers
- Anagrams
- Unique Paths
- Unique Paths II
- Triangle
- Maximum Subarray(最大子串和问题)
- House Robber
- House Robber II
- Happy Number
- Interlaving String
- Minimum Path Sum
- Edit Distance
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock II
- Best Time to Buy and Sell Stock III
- Best Time to Buy and Sell Stock IV
- Decode Ways
- N-Queens
- N-Queens II
- Restore IP Addresses
- Combination Sum
- Combination Sum II
- Combination Sum III
- Construct Binary Tree from Inorder and Postorder Traversal
- Construct Binary Tree from Preorder and Inorder Traversal
- Longest Consecutive Sequence
- Word Search
- Word Search II
- Word Ladder
- Spiral Matrix
- Jump Game
- Jump Game II
- Longest Substring Without Repeating Characters
- First Missing Positive
- Sort Colors
- Search for a Range
- First Bad Version
- Search Insert Position
- Wildcard Matching