首页 > 解决方案 > 回溯如何在 Python 中工作

问题描述

我想出了这段从 Youtube 学习的代码。我使用它通过执行回溯来解决数独问题。

import pandas as pd
import numpy as np


raw = pd.read_csv(r'C:\Users\Administrator\Dropbox\Python_Learning\debaisudoku.csv', header = None)
sudoku = np.nan_to_num(raw)

def possible(x,y,n):
    # global sudoku
    for i in range(0,9):
        if sudoku[i][y] == n:
            return False
    for i in range(0,9):
        if sudoku[x][i] == n:
            return False
        x0 = (x//3) * 3
        y0 = (y//3) * 3
    for i in range(0,3):
        for j in range(0,3):
            if sudoku[x0+i][y0+j] == n:
                return False
    return True

def solve():
    # global sudoku
    for x in range(9):
        for y in range(9):
            if sudoku[x][y] == 0:
                for n in range(1,10):
                    if possible(x,y,n):
                        sudoku[x][y] = n
                        if solve(): return True
                    sudoku[x][y] = 0
                return False
    print(sudoku)
solve()

一切都很好,我理解除了这些代码行之外的代码:

    if possible(x,y,n):
        sudoku[x][y] = n
        if solve(): return True
    sudoku[x][y] = 0
return False

Python 如何运行、循环和记住位置然后继续计算上次使用的数字?顺便说一句,如果可能的话,请告诉我如何在 VBA 中执行回溯。我已经尝试过使用 if 条件,但没有任何效果。

非常感谢,我很感激任何答案。

标签: pythonbacktrackingsudoku

解决方案


在 youtube 上看到电脑发烧友剧集后,我也一直在 VBA 中尝试它。

我想如果你想在 VBA 中“返回”,你需要使用“退出函数”功能。

当在 Excel 工作表中使用前 9*9 单元格作为网格时,此代码对我有用,在确认消息框后,数独将自行重置,我不知道为什么会发生这种情况。

如果有人知道更简洁的编码方式,我会很高兴知道,希望对您有所帮助!

Function possible(y, x, n) As Boolean
    For i = 1 To 9
        If Cells(y, i) = n Then
        possible = False
        Exit Function
        End If
    Next i
    For i = 1 To 9
        If Cells(i, x) = n Then
        possible = False
        Exit Function
        End If
    Next i

x0 = ((x - 1) \ 3) * 3
y0 = ((y - 1) \ 3) * 3
For i = 1 To 3
   For j = 1 To 3
    If Cells(y0 + i, x0 + j) = n Then
    possible = False
    Exit Function
    End If
    Next j
  Next i
possible = True

End Function

Function solve()


For y = 1 To 9
    For x = 1 To 9
        If Cells(y, x).Value = 0 Then
            For n = 1 To 10
                Debug.Print (n)
                If n = 10 Then
                    Exit Function
                End If
                    If possible(y, x, n) = True Then
                        Cells(y, x).Value = n
                        solve
                        Cells(y, x).Value = 0
                    End If
            Next n
        End If
    Next x
Next y

MsgBox ("solved!")

End Function

Sub solve_sudoku()
solve
End Sub 

推荐阅读