回溯如何在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中执行回溯。我已经尝试过goto与if条件,但没有任何效果。

非常感谢,感谢您的答复。

用户名

我在youtube上看到计算机迷集之后,也一直在VBA中尝试过它。

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

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

如果有人知道更干净的编码方式,我将很高兴知道,希望这对您有所帮助!

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 

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章