题目描述:
Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules.
The Sudoku board could be partially filled, where empty cells are filled with the character '.'
.
A partially filled sudoku which is valid.
Note:
A valid Sudoku board (partially filled) is not necessarily solvable. Only the filled cells need to be validated.
我的思路:
没怎么玩过数独,怎么完成的规则倒是了解,但是什么样算是一个正确的数独题目还是不确定,也像完成之后一样验证?每个数字在所在的行和列上都是唯一的?
查了下。。还有一个要求是每个九宫格也要是1-9。那就忽略掉未填好的位置,按行,列和九宫格检验就行了。
我的代码:
def isValidSudoku(self, board):
"""
:type board: List[List[str]]
:rtype: bool
"""
flag1 = 1
for row in board:
if not self.isUnit(row):
flag1 = 0
flag2 = 1
for col in zip(*board):
if not self.isUnit(col):
flag2 = 0
flag3 = 1
for i in (0, 3, 6):
for j in (0, 3, 6):
square = [board[x][y] for x in range(i, i + 3) for y in range(j, j + 3)]
if not self.isUnit(square):
flag3 = 0
return bool((flag1 and flag2 and flag3))
def isUnit(self, unit):
unit = [i for i in unit if i != '.']
return len(set(unit)) == len(unit)
学到:
- 对于一个二维数组,按行循环:
按列循环:for row in board:
for col in zip(*board):
- 用len(num) == len(set(num))是一个很好的检查是否有重复的方法。
- 在创建一个新的列表的时候可以直接在里面写循环,很方便。
square = [board[x][y] for x in range(i, i + 3) for y in range(j, j + 3)]
- 在类中调用方法的时候加上self.。