题解 | #Sudoku#
Sudoku
https://www.nowcoder.com/practice/78a1a4ebe8a34c93aac006c44f6bf8a1
def check(r,c):
pjr = pj[r]
clr = cl[c]
flr = fl[r//3*3+c//3]
myset = set(pjr+clr+flr)
return set([1,2,3,4,5,6,7,8,9])-myset
def change(r,c,i):
pj[r][c] = i
cl[c][r] = i
fl[r//3*3+c//3][r%3*3+c%3] = i
pj,cl,fl = [],[],[]
for _ in range(9):
pj.append(list(map(int,input().split())))
for i in range(9):
cl.append([rl[i] for rl in pj])
fi = i//3
fj = i % 3
tl = []
for j in range(fi*3,fi*3+3):
for k in range(fj*3,fj*3+3):
tl.append(pj[j][k])
fl.append(tl)
zl = []
for i in range(9):
for j in range(9):
if pj[i][j] == 0:
zl.append([i,j])
def dfs(zi):
if zi==len(zl):
return 1
r,c=zl[zi]
ns = check(r,c)
# print(ns)
if ns:
for i in ns:
change(r,c,i)
if dfs(zi+1):
return 1
change(r,c,0)
else:
return
dfs(0)
for rl in pj:
print(*rl)
一开始超时,尝试使用空间换时间,存储一个行的数组,一个列的数组,一个9宫格的数组,遍历出可能可以填的值,再存储一个数独中0的二维索引数组,遍历二维索引数组,什么时候所有的0全部有值填入,什么时候深搜结束
