74 lines
2.5 KiB
Python
74 lines
2.5 KiB
Python
|
class Solution:
|
||
|
def isValidSudoku(self, board: list[list[str]]) -> bool:
|
||
|
plates = []
|
||
|
for l in board:
|
||
|
plates.append([])
|
||
|
for ch_num in l:
|
||
|
if ch_num.isalnum():
|
||
|
num = int(ch_num[0])
|
||
|
else:
|
||
|
num = -1
|
||
|
plates[-1].append(num)
|
||
|
def judge_1(plates, i, j):
|
||
|
t = plates[i][j]
|
||
|
for idx, num in enumerate(plates[i]):
|
||
|
if idx == j: continue
|
||
|
if num == t: return False
|
||
|
return True
|
||
|
|
||
|
def judge_2(plates, i, j):
|
||
|
t = plates[i][j]
|
||
|
l = []
|
||
|
for idx in range(0, 9):
|
||
|
l.append(plates[idx][j])
|
||
|
for idx, num in enumerate(l):
|
||
|
if idx == i: continue
|
||
|
if num == t: return False
|
||
|
return True
|
||
|
|
||
|
def judge_3(plates, i, j):
|
||
|
row = i // 3 * 3
|
||
|
col = j // 3 * 3
|
||
|
l = []
|
||
|
for idx1 in range(row, row + 3):
|
||
|
for idx2 in range(col, col + 3):
|
||
|
if idx1 == i and idx2 ==j: continue
|
||
|
l.append(plates[idx1][idx2])
|
||
|
for idx,num in enumerate(l):
|
||
|
if num == plates[i][j]:
|
||
|
return False
|
||
|
return True
|
||
|
|
||
|
for i in range(0, 9):
|
||
|
for j in range(0, 9):
|
||
|
if plates[i][j] == -1: continue
|
||
|
if not judge_1(plates, i, j):
|
||
|
return False
|
||
|
if not judge_2(plates, i, j):
|
||
|
return False
|
||
|
if not judge_3(plates, i, j):
|
||
|
return False
|
||
|
return True
|
||
|
|
||
|
board = [["5","3",".",".","7",".",".",".","."]
|
||
|
,["6",".",".","1","9","5",".",".","."]
|
||
|
,[".","9","8",".",".",".",".","6","."]
|
||
|
,["8",".",".",".","6",".",".",".","3"]
|
||
|
,["4",".",".","8",".","3",".",".","1"]
|
||
|
,["7",".",".",".","2",".",".",".","6"]
|
||
|
,[".","6",".",".",".",".","2","8","."]
|
||
|
,[".",".",".","4","1","9",".",".","5"]
|
||
|
,[".",".",".",".","8",".",".","7","9"]]
|
||
|
|
||
|
sol = Solution()
|
||
|
print(sol.isValidSudoku(board=board))
|
||
|
board = [["8","3",".",".","7",".",".",".","."]
|
||
|
,["6",".",".","1","9","5",".",".","."]
|
||
|
,[".","9","8",".",".",".",".","6","."]
|
||
|
,["8",".",".",".","6",".",".",".","3"]
|
||
|
,["4",".",".","8",".","3",".",".","1"]
|
||
|
,["7",".",".",".","2",".",".",".","6"]
|
||
|
,[".","6",".",".",".",".","2","8","."]
|
||
|
,[".",".",".","4","1","9",".",".","5"]
|
||
|
,[".",".",".",".","8",".",".","7","9"]]
|
||
|
print(sol.isValidSudoku(board=board))
|