题解 | #Sudoku# 递归函数
Sudoku
https://www.nowcoder.com/practice/78a1a4ebe8a34c93aac006c44f6bf8a1
l_r=[] # 每行 1*9 for i in range(9): s=list(map(int,input().split())) l_r.append(s) #print(l_r) def check(l_r,i,j): for k in range(9): if l_r[i][k]==l_r[i][j] and k!=j: return False for k in range(9): if l_r[k][j]==l_r[i][j] and k!=i: return False m = 3*(i // 3) #m,n分别是i,j位置所在的3*3格子的最左上角的位置 n = 3*(j // 3) for k in range(3): for z in range(3): if (l_r[m+k][n+z] == l_r[i][j]) and ((m+k) != i) and ((n+z) != j): #判断所在3*3格子是否有重复的数据 return False return True def find_sudoku(l_r): num=[1,2,3,4,5,6,7,8,9] for i in range(9): for j in range(9): if l_r[i][j]==0: for n in num: l_r[i][j]=n if check(l_r,i,j) and find_sudoku(l_r): #l_r[i][j]=n #不能直接判定该位置可以填n return True #n满足条件返回true l_r[i][j]=0 #n不满足上述条件,取值恢复为0 return False # 所有n都不满足条件,返回false(该数独不合法) return True find_sudoku(l_r) for i in l_r: for j in i: print(j,end=' ') print() ''' 0 9 5 0 2 0 0 6 0 0 0 7 1 0 3 9 0 2 6 0 0 0 0 5 3 0 4 0 4 0 0 1 0 6 0 7 5 0 0 2 0 7 0 0 9 7 0 3 0 9 0 0 2 0 0 0 9 8 0 0 0 0 6 8 0 6 3 0 2 1 0 5 0 5 0 0 7 0 2 8 3 '''