forked from shuboc/LeetCode-2
-
Notifications
You must be signed in to change notification settings - Fork 6
/
valid-sudoku.py
42 lines (39 loc) · 1.6 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
# Time: O(n^2)
# Space: O(n)
#
# 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:
# @param board, a 9x9 2D array
# @return a boolean
def isValidSudoku(self, board):
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)