forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 1
/
valid-sudoku.py
48 lines (43 loc) · 1.7 KB
/
valid-sudoku.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# Time: O(9^2)
# Space: O(9)
# Determine if a Sudoku is valid,
# according to: Sudoku Puzzles - The Rules.
#
# The Sudoku board could be partially filled,
# where empty cells are filled with the character '.'.
#
# A partially filled sudoku which is valid.
#
# Note:
# A valid Sudoku board (partially filled) is not necessarily solvable.
# Only the filled cells need to be validated.
class Solution(object):
def isValidSudoku(self, board):
"""
:type board: List[List[str]]
:rtype: bool
"""
for i in xrange(9):
if not self.isValidList([board[i][j] for j in xrange(9)]) or \
not self.isValidList([board[j][i] for j in xrange(9)]):
return False
for i in xrange(3):
for j in xrange(3):
if not self.isValidList([board[m][n] for n in xrange(3 * j, 3 * j + 3) \
for m in xrange(3 * i, 3 * i + 3)]):
return False
return True
def isValidList(self, xs):
xs = filter(lambda x: x != '.', xs)
return len(set(xs)) == len(xs)
if __name__ == "__main__":
board = [[1, '.', '.', '.', '.', '.', '.', '.', '.'],
['.', 2, '.', '.', '.', '.', '.', '.', '.'],
['.', '.', 3, '.', '.', '.', '.', '.', '.'],
['.', '.', '.', 4, '.', '.', '.', '.', '.'],
['.', '.', '.', '.', 5, '.', '.', '.', '.'],
['.', '.', '.', '.', '.', 6, '.', '.', '.'],
['.', '.', '.', '.', '.', '.', 7, '.', '.'],
['.', '.', '.', '.', '.', '.', '.', 8, '.'],
['.', '.', '.', '.', '.', '.', '.', '.', 9]]
print Solution().isValidSudoku(board)