题目:
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-9without repetition. - Each column must contain the digits
1-9without repetition. - Each of the 9
3x3sub-boxes of the grid must contain the digits1-9without repetition.
算法思路:
判断每行每列每个九宫格是否出现重复数字:设立一个列表,用于标记1-9数字出现的次数,出现的时候,在列表中对应的索引处加一,同时判断若该数字出现次数超过一次,则返回flase. 如果每行每列每个九宫格都没有重复数字,则返回true。
代码展示:
def isValidSudoku(self, board):
"""
:type board: List[List[str]]
:rtype: bool
"""
temp = []
for i in range(10):
temp.append(0)
#判断每行是否有重复数字
for i in board:
tmp = temp[::]
for j in range(9):
if i[j] != '.':
tmp[int(i[j] )] += 1
if tmp[int(i[j])] > 1:
return False
#判断每列是否有重复数字
for j in range(9):
tmp = temp[::]
for i in range(9):
if board[i][j] != '.':
tmp[int(board[i][j] )] += 1
if tmp[int(board[i][j] )] > 1:
return False
#判断每个九宫格是否有重复数字
for i in range(3):
i *= 3
for j in range(3):
j *= 3
tmp = temp[::]
for k in range(i, 3 + i):
for l in range(j,j+3):
if board[k][l] != '.':
tmp[int(board[k][l])] += 1
if tmp[int(board[k][l])] > 1:
return False
return True
结果展示: