Leetcode 36. Valid Sudoku

Determine if a 9x9 Sudoku board is valid. Only the filled cells need to be validated according to the following rules:

Each row must contain the digits 1-9 without repetition.
Each column must contain the digits 1-9 without repetition.
Each of the 9 3x3 sub-boxes of the grid must contain the digits 1-9 without repetition.

1. 思路

题目的意思就是数独游戏

  1. 行中要包含1-9,不重复
  2. 列中要包含1-9,不重复
  3. 9x9方格按照3x3划分的每个小棋盘,其中的数也要包含1-9,不重复
    一个一个条件实现就好

2. Code

class Solution:
    def __init__(self):
        self.board = None

    def satisfy9(self, ele):
        ele = [i for i in ele if i != '.']
        return len(set(ele)) == len(ele)

    def row_valid(self):
        for row in self.board:
            if not self.satisfy9(row):
                return False
        return True

    def col_valid(self):
        for col in zip(*self.board):
            if not self.satisfy9(col):
                return False
        return True

    def cell_valid(self):
        for i in [0, 3, 6]:
            for j in [0, 3, 6]:
                cell = [self.board[x][y] for x in range(i, i+3) for y in range(j, j+3)]
                if not self.satisfy9(cell):
                    return False
        return True

    def isValidSudoku(self, board) -> bool:
        self.board = board
        return self.row_valid() and self.col_valid() and self.cell_valid()

中间有几个操作需要提一下:

  1. 矩阵快速转置:zip(*array)
  2. 二维数组快速初始化: cell = [self.board[x][y] for x in range(i, i+3) for y in range(j, j+3)]

更多刷题小技巧参考我的博客:传送门


欢迎评论和点赞

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值