【LeetCode】36. Valid Sudoku 解题报告(Python)

题目分析:

这一题比较简单,甚至我觉得有耐心可以不用循环写出来(滑稽),用循环就时取出每行、每列、每个小格子里非’.'的值,再判断是否有重复值即可,可以用set或者dict取判断,我觉得dict要简单一些,不存在就加进去,存在返回False。
【LeetCode】36. Valid Sudoku 解题报告(Python)_第1张图片
关于行列没什么说的,而小格子的坐标有点难度,[int(i/3)*3 + int(j/3)]可以理解为第几个小格子,[int(i%3)*3 + int(j%3)]可以理解为小格子中的第几个元素,你可以写几个格子的坐标找一下这个规律。

测试代码:

class Solution:
    def isValidSudoku(self, board):
        for i in range(9):
            #分别储存一行,一列,一个小方格
            heng, shu, fang = {}, {}, {}
            for j in range(9):
                #行,首先排除'.'
                if board[i][j] != '.':
                    #不在则加入字典,在了就是重复返回False
                    if board[i][j] not in heng: heng.update({board[i][j]:0})
                    else:   return False
                #列,首先排除'.'
                if board[j][i] != '.':
                    # 不在则加入字典,在了就是重复返回False
                    if board[j][i] not in shu: shu.update({board[j][i]:0})
                    else:   return False
                #小方格,首先排除'.',[int(i/3)*3 + int(j/3)]可以理解为第几个小格子,[int(i%3)*3 + int(j%3)]可以理解为小格子中的第几个元素
                if board[int(i/3)*3 + int(j/3)][int(i%3)*3 + int(j%3)] != '.':
                    # 不在则加入字典,在了就是重复返回False
                    if board[int(i/3)*3 + int(j/3)][int(i%3)*3 + int(j%3)] not in fang: fang.update({board[int(i/3)*3 + int(j/3)][int(i%3)*3 + int(j%3)]:0})
                    else:   return False
        return True

print(Solution().isValidSudoku([
  ["5","3",".",".","7",".",".",".","."],
  ["6",".",".","1","9","5",".",".","."],
  [".","9","8",".",".",".",".","6","."],
  ["8",".",".",".","6",".",".",".","3"],
  ["4",".",".","8",".","3",".",".","1"],
  ["7",".",".",".","2",".",".",".","6"],
  [".","6",".",".",".",".","2","8","."],
  [".",".",".","4","1","9",".",".","5"],
  [".",".",".",".","8",".",".","7","9"]
])) #提交时请删除print

你可能感兴趣的:(python,LeetCode,LeetCode题目记录)