有效的数独-力扣解题
判断一个9x9的数独是否有效。只需要根据以下规则,验证已经填入的数字是否有效即可
- 数字 1-9 在每一行只能出现一次
- 数字 1-9 在每一列只能出现一次
- 数字 1-9 在每一个以粗实线分隔的 3x3 宫内只能出现一次
def dfs(table:list, x:int, y:int) ->None:
if x == 9:
print(table)
exit(0)
if table[x][y] == 0:
for i in range(1, 10):
flag = check(table, x, y, i)
if flag:
table[x][y] = i
dfs(table, x + (y + 1) // 9, (y+1)%9)
table[x][y] = 0
else:
dfs(table, x + (y + 1) // 9, (y + 1) % 9)
def check(table, x, y, z) ->bool:
# 检测同行同列
for i in range(9):
if table[x][i] == z: return False
if table[i][y] == z: return False
# 检测小九宫格
for i in range((x // 3) * 3, (x // 3 + 1) * 3):
for j in range((y // 3) * 3, (y // 3 + 1) * 3):
if table[i][j] == z: return False
return True
table = [
[0,0,5,3,0,0,0,0,0],
[8,0,0,0,0,0,0,2,0],
[0,7,0,0,1,0,5,0,0],
[4,0,0,0,0,5,3,0,0],
[0,1,0,0,7,0,0,0,6],
[0,0,3,2,0,0,0,8,0],
[0,6,0,5,0,0,0,0,9],
[0,0,4,0,0,0,0,3,0],
[0,0,0,0,0,9,7,0,0]
]
dfs(table, 0, 0)