博文中会简要介绍Leetcode P0037题目分析及解题思路。
“Sudoku Solver”是“看图看题说话”的风格,主要运用深度搜索。这里可以不用HashTable来记录数字出现个数,这样可以减少时间开销。
Write a program to solve a Sudoku puzzle by filling the empty cells.
A sudoku solution must satisfy all of the following rules:
- Each of the digits 1-9 must occur exactly once in each row.
- Each of the digits 1-9 must occur exactly once in each column.
- Each of the the digits 1-9 must occur exactly once in each of the 9 3x3 sub-boxes of the grid.
Empty cells are indicated by the character ‘.’.
按题目要求的规则写出判断公式,并且通过取出所有空格子连成链表来便利深度搜索。这里我是采取了相对麻烦的方法,即每个格子都重新判断,其实可以维护三个规则的布尔矩阵用于判断,在深度搜索的时候向下传递并且更新。这里就不再赘述。
以下是Java的题解代码实现。