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.
数独的规则:数独的每一行、每一列、9个九宫格里的数字只能是0-9,且不能重复。
经典一点,就暴力破解,三个规则都过一遍
class Solution(object):
def isValidSudoku(self, board):
"""
:type board: List[List[str]]
:rtype: bool
"""
for i in range(9):
if not self.isValidNine(board[i]):
return False
col = [c[i] for c in board]
if not self.isValidNine(col):
return False
for i in [0, 3, 6]:
for j in [0, 3, 6]:
block = [board[s][t] for s in [i, i+1, i+2] for t in [j, j+1, j+2]]
if not self.isValidNine(block):
return False
return True
def isValidNine(self, row):
map = {}
for c in row:
if c != '.':
if c in map:
return False
else:
map[c] = True
return True
网上找了一个非常短小的代码,值得学习,方法是记录所有出现过的行、列、块的数字及相应位置,最后判断是否有重复,用set操作精简代码
class Solution(object):
def isValidSudoku(self, board):
"""
:type board: List[List[str]]
:rtype: bool
"""
seen = []
for i, row in enumerate(board):
for j, col in enumerate(row):
if col != '.':
seen += [(col, j), (i, col), (i/3, j/3, col)]
return len(seen) == len(set(seen))