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-9,不重复
- 列中要包含1-9,不重复
- 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()
中间有几个操作需要提一下:
- 矩阵快速转置:zip(*array)
- 二维数组快速初始化: cell = [self.board[x][y] for x in range(i, i+3) for y in range(j, j+3)]
更多刷题小技巧参考我的博客:传送门
欢迎评论和点赞