【发布时间】:2023-05-28 20:07:01
【问题描述】:
我正在研究算法理论及其可能的解决方法。在这种情况下,我在回溯方面遇到了一些问题。 我想写一个填充数独的函数。但它不打印任何东西。错误在哪里? 函数 defsett(i,j) 将两个数字作为所选数字的坐标作为输入,并设置两个整数(w 和 o)作为输入数字的 3x3 部分的起点。 相反,数独函数递归地尝试用数独规则填充矩阵。
# defsett = returns the coordinates of the first cell of the section 3x3
# where is the cell [i,j]
def defsett(i,j):
if(0<=i<=2):
if(0<=j<=2):
return (0,0)
elif(3<=j<=5):
return (0,3)
elif(6<=j<=8):
return (0,6)
elif(3<=i<=5):
if(0<=j<=2):
return (3,0)
elif(3<=j<=5):
return (3,3)
elif(6<=j<=8):
return (3,6)
else:
if(0<=j<=2):
return (6,0)
elif(3<=j<=5):
return (6,3)
elif(6<=j<=8):
return (6,6)
M = [[5,3,0,0,7,0,0,0,0],
[6,0,0,1,9,5,0,0,0],
[0,9,8,0,0,0,0,6,0],
[8,0,0,0,6,0,0,0,3],
[4,0,0,8,0,3,0,0,1],
[7,0,0,0,2,0,0,0,6],
[0,6,0,0,0,0,2,8,0],
[0,0,0,4,1,9,0,0,5],
[0,0,0,0,8,0,0,7,9]]
# n = matrix side
# i = index of rows
# j = index of cols
def sudoku(n,i,j,M):
if(i==n):
print(M)
elif(j==n):
j=0
i=i+1
sudoku(n,i,j,M)
else:
if(M[i][j]==0):
for number in range(1,n+1):
xInRows = False
xInCols = False
xInSection = False
# checking if number already present in this row
for k in range(n):
if (number == M[i][k]):
xInRows = True
# checking if number already present in this cols
for k in range(n):
if(number == M[k][j]):
xInCols = True
w,o=defsett(i,j) # first cell of this section
# checking if number already present in this section 3x3
for t in range(w,w+3):
for b in range(o,o+3):
if(number == M[t][b]):
xInSection = True
if(not(xInRows) and not(xInCols) and not(xInSection)):
M[i][j] = x
sudoku(n,i,j+1,M)
else:
sudoku(n,i,j+1,M)
sudoku(9,0,0,M)
-----
For this input works:
M = [[5,3,0,0,7,0,0,0,0],
[6,0,0,1,9,5,0,4,8],
[1,9,8,3,4,2,5,6,7],
[8,5,9,7,6,1,4,2,3],
[4,2,6,8,5,3,7,9,1],
[7,1,3,9,2,4,8,5,6],
[9,6,1,5,3,7,2,8,4],
[2,8,7,4,1,9,6,3,5],
[3,4,5,0,8,6,1,7,9]]
For this doesn't:
M = [[5,3,0,0,7,0,0,0,0],
[6,0,0,1,9,5,0,0,8],
[1,9,8,3,4,2,5,6,7],
[8,5,9,7,6,1,4,2,3],
[4,2,6,8,5,3,7,9,1],
[7,1,3,9,2,4,8,5,6],
[9,6,1,5,3,7,2,8,4],
[2,8,7,4,1,9,6,3,5],
[3,4,5,0,8,6,1,7,9]]
【问题讨论】:
-
你知道变量可以超过1个字符吗?
-
解释一下你想说什么……我不明白
-
你的代码很难理解,因为你的变量名很神秘。
-
你是对的。对不起。我要编辑它;)
标签: python python-3.x backtracking sudoku recursive-backtracking