首页 > 解决方案 > 如何在返回 None 的函数中使用变量?

问题描述

我有以下功能,它是用来解决数独网格的。如何更改代码以使其返回已解决的矩阵,以便我可以将其用于其他用途,而不仅仅是打印它?该函数基本上使用递归来尝试数独网格的所有可能解决方案,如果它属于某个位置,则填写一个数字。来源:https ://www.youtube.com/watch?v=G_UYXzGuqvM&t=455s

matrix = np.array([[9,0,7,   1,0,0,   0,0,0],
                   [0,0,0,   0,0,0,   0,0,0],
                   [5,0,0,   3,0,0,   0,6,9],

                   [0,0,1,   6,5,0,   8,0,0],
                   [0,3,0,   0,8,0,   0,4,0],
                   [0,0,6,   0,3,9,   1,0,0],

                   [4,2,0,   0,0,6,   0,0,8],
                   [0,0,0,   0,0,0,   0,0,0],
                   [0,0,0,   0,0,2,   5,0,7]])

def grid(i,j): # function which splits the matrix up into 9 grids
    if i < 3 and j < 3:
        return matrix[0:3,0:3]
    elif  i < 3 and 3 <= j < 6 :
        return matrix[0:3,3:6]
    elif  i < 3 and 6 <= j < 9 :
        return matrix[0:3,6:9]
    elif  3 <= i < 6 and j < 3 :
        return matrix[3:6,0:3]
    elif  3 <= i < 6 and 3 <= j < 6 :
        return matrix[3:6,3:6]
    elif  3 <= i < 6 and 6 <= j < 9:
        return matrix[3:6,6:9]
    elif  6 <= i < 9 and j < 3 :
        return matrix[6:9,0:3]
    elif  6 <= i < 9 and 3 <= j < 6 :
        return matrix[6:9,3:6]
    elif  6 <= i < 9 and 6 <= j < 9 :
        return matrix[6:9,6:9] #

def possible(i,j,n): # function which tells us if a number is possible in a certain position
    if all(matrix[i][m] != n and matrix[m][j] != n for m in range(9)) and n not in grid(i,j):
        return True
    else:
        return False

def solve(): # function which solves the puzzle and fills in correct digits
    global matrix
    for i in range(9):
        for j in range(9):
            if matrix[i][j] == 0:
                for n in range(1,10):
                    if possible(i,j,n):
                        matrix[i][j] = n
                        solve()
                        matrix[i][j] = 0
                return
    print(matrix)


solve()

我曾尝试使用return matrix,但这只是返回原始矩阵

标签: pythonfunctionbacktracking

解决方案


您的代码的问题是您正在处理全局矩阵。在递归调用的深处,您可以找到解决方案(并打印它),但是当返回堆栈时,您会将所有字段重置为 0。(请参阅 chepner 的评论。)

鉴于您正在以“程序风格”进行编码,为什么不使用第二个全局变量(solution比如说)并分配一个深层副本。

from copy import deepcopy

...


solution = deepcopy(matrix)

当然,您也可以以更实用的方式重构代码。


推荐阅读