leetcode 每日一题 36. 有效的数独
一次遍历
思路:
对二维数组每个元素进行遍历,遍历的同时记录下当前元素在行、列和3x3格中出现的次数,如果大于1返回False,遍历结束则返回True。
代码:
class Solution: def isValidSudoku(self, board: List[List[str]]) -> bool: rows = [{} for i in range(9)] columns = [{} for i in range(9)] boxes = [{} for i in range(9)] for i in range(9): for j in range(9): if board[i][j] != '.': num = int(board[i][j]) boxIndex = (i//3)*3 + j//3 rows[i][num] = rows[i].get(num,0)+1 columns[j][num] = columns[j].get(num,0)+1 boxes[boxIndex][num] = boxes[boxIndex].get(num,0)+1 if rows[i][num]>1 or columns[j][num] >1 or boxes[boxIndex][num]>1: return False return True