Leetcode 36. Valid Sudoko
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.
思路: 检查每一行,每一列,每一个3*3的submatrix是不是出现了重复的数字,如果出现了,return False。如果没有renturn True。 L21-L23在Python 3中已经可以省略,如果A是一个list of lists, ''.join(A) 可以直接返回一个string。但是python2中还需要先将A变成一个list。
Tip: 在一个lists of list中如何取出一个submatirx? 假设 row = 1:4, col = 2:5。 可以使用
A = [row[2:5] for row in M[1:4]]
1 class Solution(object): 2 def isValidSudoku(self, board): 3 """ 4 :type board: List[List[str]] 5 :rtype: bool 6 """ 7 for i in range(9): 8 if self.isValidString(board[i]) == False: 9 return False 10 11 12 for i in range(9): 13 string = [board[j][i] for j in range(9)] 14 string = ''.join(string) 15 if self.isValidString(string) == False: 16 return False 17 18 for i in range(3): 19 for j in range(3): 20 string = [row[3*j: 3*j + 3] for row in board[3*i: 3*i+3]] 21 ans = [] 22 for k in range(len(string)): 23 ans += string[k] 24 string = ''.join(ans) 25 if self.isValidString(string) == False: 26 return False 27 return True 28 29 def isValidString(self, numbers): 30 isused = [0] * 10 31 for j in range(9): 32 if numbers[j] == '1' and isused[1] == 0: 33 isused[1] = 134 elif numbers[j] == '2' and isused[2] == 0: 35 isused[2] = 136 elif numbers[j] == '3' and isused[3] == 0: 37 isused[3] = 138 elif numbers[j] == '4' and isused[4] == 0: 39 isused[4] = 140 elif numbers[j] == '5' and isused[5] == 0: 41 isused[5] = 142 elif numbers[j] == '6' and isused[6] == 0: 43 isused[6] = 144 elif numbers[j] == '7' and isused[7] == 0: 45 isused[7] = 146 elif numbers[j] == '8' and isused[8] == 0: 47 isused[8] = 148 elif numbers[j] == '9' and isused[9] == 0: 49 isused[9] = 150 elif numbers[j] == '.': 51 continue 52 else: 53 return False 54 return True
当然help function可以使用hash table的方式来检查当然元素是不是已经存在。
1 def isValidString(self, numbers): 2 isused = {} 3 for elem in numbers: 4 if elem == '.': 5 continue 6 elif elem not in isused: 7 isused[elem] = True 8 else: 9 return False 10 return True