【问题标题】:Search a 2D list for a specific element recursively递归搜索特定元素的二维列表
【发布时间】:2014-03-28 17:20:28
【问题描述】:

findStart() 函数假设递归地搜索代表迷宫的二维列表。假设搜索此列表并找到列表中特定元素的 x 和 y(第一个和第二个索引)为“S”。但是,假设使用递归,并且 findStart() 方法不接受任何参数。我已经找到了如何使用迭代来完成它,但是我怎样才能使这个迭代变成递归呢?

def findStart():
    for a in mazeList:
        for x in a:
            if x == "S":
                xcoord = a.index("S")
                ycoord = mazeList.index(a)
                return (ycoord),(xcoord)
    return -1,-1

迷宫:

####################################
#S#  ##  ######## # #      #     # #
# #   #             # #        #   #
#   # ##### ## ###### # #######  # #
### # ##    ##      # # #     #### #
#   #    #  #######   #   ###    #E#
####################################

【问题讨论】:

  • 这些是一些非常奇怪的要求。如果一个函数没有参数,如何确定递归的终止条件?您必须使用全局变量。似乎比迭代地查找坐标更麻烦。
  • 您可以简单地创建一个执行递归的第二个(甚至是内部)函数。
  • 我对 Python 不是很熟悉,但递归确实需要传入某种参数(除非您使用全局变量,但这是 IMO 的一种坏习惯)。然后该参数用于确定是否需要再次递归调用该函数。我能想到的唯一方法是创建findStart() 调用的第二个方法,它是递归的第二个方法(第二个方法当然有参数,可能是下一个坐标)。
  • 昨天有人发了一个非常相似的问题(同样的迷宫,是python),可能有帮助:stackoverflow.com/q/22700130/2282538

标签: python recursion


【解决方案1】:

现在,作为序言,我同意上面的评论讨论,不建议在没有参数的函数上在 python 中进行递归搜索,因为您可能会遇到问题,具体取决于您的搜索如何工作以及它如何访问您的 global 变量,并且您实际上将执行由函数“管理”的迭代搜索,即它只是决定增加什么以及何时增加。

要以您描述的方式正确地进行迭代搜索,您可以将 findStart 转换为包装函数:

任一(推荐):

def findStart(mazeList):
    return findStartRec(mazeList,0,0)

或: mazeList = ... # 定义迷宫列表 def findStart(mazeList): 返回 findStartRec(mazeList,0,0)

然后求解:

def findStartRec(mazeList,x,y):
    if y >= len(mazeList):
        return -1,-1                         # We have reached the end of the maze and no result
    if x >= len(mazeList[y]):
        return findStartRec(mazeList,0,y+1)  # We have reached the end of a row, continue to the next row
    if mazeLise[y][x] == "S":
        return x,y                           # We have found the start
    else:
        return findStartRec(mazeList,x+1,y)  # Search the next spot on this row

为我工作:

>>> findStartRec(mazeList) 
(1, 1)

然后先定义,没有参数函数:

maze = """####################################
#S#  ##  ######## # #      #     # #
# #   #             # #        #   #
#   # ##### ## ###### # #######  # #
### # ##    ##      # # #     #### #
#   #    #  #######   #   ###    #E#
####################################"""
mazeList = [[x for x in row] for row in maze.split('\n')]
def findStart():
    return findStartRecu(mazeList,0,0)

然后调用:

>>> findStart()
(1,1)  

最后一点,这并不是递归搜索的最佳应用,因为这种搜索存在于非常明确和已知的范围内,即它是矩形的。递归搜索更适合诸如树、链表等非线性形状的数据结构,因为不可能使用像for 循环这样的有限映射来真正搜索它们。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-06-24
    • 2022-08-10
    • 1970-01-01
    • 2021-01-18
    • 1970-01-01
    • 2018-12-10
    • 1970-01-01
    相关资源
    最近更新 更多