【问题标题】:Why does my recursive knight code in Python only run the first stack?为什么我在 Python 中的递归骑士代码只运行第一个堆栈?
【发布时间】:2020-12-14 13:27:19
【问题描述】:

因此,代码是关于找到一个棋子从起点到终点所需的最少回合数。而且代码必须是递归的。 我对这段代码有疑问。 .我的问题是它并没有遍历所有堆栈,而是仅通过一个可能移动的“路径”,然后提供该路径所需的轮数。

例如使用 print(knight([1,1], [5,2], [])) 它返回 17 而不是 3

moves = ([1,2],[2,1],[-1,2],[-1,-2],[1,-2],[2,-1],[-2,1],[-2,-1])

def knight(start, goal, visited):
    if start == goal:
        return 0      
    else:
        visited.append(start)
        possibles =[]
        makeable= []
        for x in range(8):
            possibles.append([start[0] + moves[x][0],start[1] + moves[x][1]])
        for i in range(8):
            if possibles[i]  not in visited and possibles[i][0]<9 and possibles[i][1]<9 and possibles[i][0]>0 and possibles[i][1]>0:
                makeable.append(knight(possibles[i],goal,visited))

        if makeable:
            return min(makeable)+1
        else:
            return 99   
            
                
                  
    
print(knight([1,1], [5,2], []))

【问题讨论】:

  • 我想如果你多解释一下这段代码应该做什么以及它在你的理解中应该如何工作,会有更多的人愿意帮助你。此外,如果代码是用英文编写的,每个人都更容易理解代码。
  • 谢谢,我做到了。希望对理解有帮助

标签: python recursion chess


【解决方案1】:

我假设您的 besucht 正在存储路径。我不明白它的用途,因为它没有在代码中的任何地方使用。不管怎样,我不会再假装我在 CodeReview 上,而是回答你的问题。

错误的原因是因为您正在传递列表besucht。当您将列表作为函数参数传递时,它作为引用/指针而不是列表的 副本 传递。结果,后面的函数调用会修改原来的besucht,导致if possibles[i] in besucht出现bug。

要解决此问题,请传入路径的副本。 (显然这不是最有效的方法,但它在这里有效)。见代码。

# python
moves = ([1,2],[2,1],[-1,2],[-1,-2],[1,-2],[2,-1],[-2,1],[-2,-1])

def springerzug(start, end, path, sofar = 0):
    if start == end:
        return 0
    # Terminate if path is too long
    if len(path) > 9:
        return 999
    # omit the else
    possibles = []
    ergebnisse = [98] # default value

    for x in range(8):
        possibles.append([start[0] + moves[x][0], start[1] + moves[x][1]])

    for i in range(8):
        if 0 < possibles[i][0] < 9 and 0 < possibles[i][1] < 9 \
            and possibles[i] not in path:
                ergebnisse.append(springerzug(possibles[i], end, path.copy() + [possibles[i]]))

    return min(ergebnisse)+1
            
                
                  
    
print(springerzug([1,1], [5,2], []))

(注意:您使用 DFS 获取最短路径的代码效率极低。请搜索 Breath-First Search,这样 stackoverflow 上的其他人就不会因为您的低效代码而抨击您。)

【讨论】:

  • 谢谢老兄,我知道它效率不高,但这是我计算机科学课上的一项任务
  • @unsympathisch 接受答案会很好:)
猜你喜欢
  • 2023-01-30
  • 1970-01-01
  • 2015-04-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-17
  • 1970-01-01
  • 2021-05-11
相关资源
最近更新 更多