简体   繁体   English

在递归python函数中,如何到达调用自身的代码行之后的代码行

[英]In a recursive python function, how is the line of code reached, that comes after the line of code which calls itself

this is my code that I copied from the sudoku solver video computerphile made:这是我从数独解算器视频计算机爱好者复制的代码:

grid = [ [4, 0, 0, 0, 0, 5, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 1, 9, 8],
[3, 0, 0, 0, 8, 2, 4, 0, 0],
[0, 0, 0, 1, 0, 0, 0, 8, 0], 
[9, 0, 3, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 3, 0, 6, 7, 0], 
[0, 5, 0, 0, 0, 9, 0, 0, 0], 
[0, 0, 0, 2, 0, 0, 9, 0, 7], 
[6, 4, 0, 3, 0, 0, 0, 0, 0], ]

def possible(x, y, n):
    for i in range(0, 9):
        if grid[i][x] == n and i != y:
            return False
    for i in range(0, 9):
        if grid[y][i] == n and i != x:
            return False            
    x0 = (x // 3) * 3
    y0 = (y // 3) * 3
    for X in range(x0, x0 + 3):
        for Y in range(y0, y0 + 3):
            if grid[Y][X] == n:
                return False    
    return True


def Print(matrix):
    for i in range(9):
        print(matrix[i])


def solve():
    global grid
    for y in range(9):
        for x in range(9):
            if grid[y][x] == 0:
                for n in range(1, 10):
                    if possible(x, y, n):
                        grid[y][x] = n
                        solve()
                        grid[y][x] = 0
                return
    Print(grid)
    input("")

solve()

I want to know how the grid[y][x] = 0 located inside the solve() function ever gets reached?我想知道如何到达位于solve()函数内的grid[y][x] = 0 Wouldn't Python go back to the beginning of the solve() function every time it reaches the line above, which is solve() ?不会的Python回到年初solve()函数每次到达上面的行时间,这是solve()

So how does the function solve() run?那么函数solve()如何运行的呢?

somewhere in solving the puzzle the answer to possible(x, y, n) will be false for every instance of the for-loop, in this case the code jumps to return statement for solve method.在解决难题的某个地方,对于 for 循环的每个实例, possible(x, y, n)的答案都是假的,在这种情况下,代码跳转到solve方法的return语句。 in this time, the program runs the grid[y][x] = 0 part!这时候程序运行grid[y][x] = 0部分!

you can see more example of recursive functions here .你可以在这里看到更多递归函数的例子。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM