36. Valid Sudoku
problem description
Determine if a 9x9 Sudoku board is valid. Only the filled cells need to be validated according to the following rules:
Each row must contain the digits
1-9
without repetition.Each column must contain the digits
1-9
without repetition.Each of the 9
3x3
sub-boxes of the grid must contain the digits1-9
without repetition.
A partially filled sudoku which is valid.
The Sudoku board could be partially filled, where empty cells are filled with the character '.'
.
Example 1:
Example 2:
Note:
A Sudoku board (partially filled) could be valid but is not necessarily solvable.
Only the filled cells need to be validated according to the mentioned rules.
The given board contain only digits
1-9
and the character'.'
.The given board size is always
9x9
.
algorithm thought
使用hash表存放之前访问过的信息,可以保证每个位置只访问一次。这也类似一些一维数组题目,需要我们在O(n)时间复杂度内解决问题。这里需要保存数独规则下,当前位置对后面位置的影响。在数独中,行和列以及block中不能出现一样的数字。每次将访问的数字3个规则保存到hash表中,这种思路其实不难得出,难得出的是该如果在hash表中保存信息。如何保存可以看代码。
code
algorithm analysis
算法中有两个for循环,循环中进行的操作是O(1)的,最后时间复杂度是O(n²)
Last updated