Leetcode 36. Valid Sudoku (python)
程序员文章站
2022-03-23 18:12:59
...
题目
解法:
这道题不难,关键在于找到(i,j)位置的元素怎样同时判断row,col和box的情况。
对于row,col和box,分别对应9行,9列和9个box。用三个长度为9元素为字典的list来对应
class Solution:
def isValidSudoku(self, board: List[List[str]]) -> bool:
row_dic = [collections.defaultdict(int) for _ in range(9)]
col_dic = [collections.defaultdict(int) for _ in range(9)]
box_dic = [collections.defaultdict(int) for _ in range(9)]
print(row_dic)
for i in range(9):
for j in range(9):
num = board[i][j]
if num != '.':
row_dic[i][num]+=1
col_dic[j][num]+=1
box_id = (i//3)*3 + j//3
box_dic[box_id][num]+=1
if row_dic[i][num]>1 or col_dic[j][num]>1 or box_dic[box_id][num]>1:
return False
return True