简体   繁体   English

递归到迭代 DFS python

[英]recursive to iterative DFS python

I am trying to convert recursive code to iterative.我正在尝试将递归代码转换为迭代代码。 The task is to find the largest region (connected cells consisting of ones) in the grid.任务是在网格中找到最大的区域(由单元组成的连接单元)。

The code is referenced from here: https://www.geeksforgeeks.org/find-length-largest-region-boolean-matrix/ I have tried using stack and a loop to replace recursion but it is not working代码从这里引用: https://www.geeksforgeeks.org/find-length-largest-region-boolean-matrix/我尝试使用堆栈和循环来替换递归,但它不起作用

here is the code I have tried and it does not reproduce the same result as with recursive approach.这是我尝试过的代码,它不会重现与递归方法相同的结果。

I have tested with我已经测试过

M = np.array([[0, 0, 1, 1, 0], [1, 0, 1, 1, 0], [0, 1, 0, 0, 0], [0, 0, 0, 0, 2],[0, 0, 0, 1, 0],[0, 0, 3, 0, 0]]) 

def DFS(M, row, col, visited): 
    rowNbr = [-1, -1, -1, 0, 0, 1, 1, 1]  
    colNbr = [-1, 0, 1, -1, 1, -1, 0, 1]  

    # Mark this cell as visited  
    visited[row][col] = True
    stack = [] 

    for k in range(8): 
        if (isSafe(M, row + rowNbr[k],  
                   col + colNbr[k], visited)): 

            stack.push(M[row][col])
            row = row + rowNbr[k]
            col = col + colNbr[k]
            for k in range(8): 
                if (isSafe(M, row + rowNbr[k],  
                    col + colNbr[k], visited)):
                    stack.push(M[row][col])

The general structure for DFS using a stack is使用堆栈的 DFS 的一般结构是

stack = [] # initialize Stack
visited = set() # initialize hash table for looking at visited nodes
stack.append(startNode) # put in the start node

while len(stack) != 0: # check whether there is anything in the To-Do list
   newNode = stack.pop() # get next node to visit
   if newNode not in visited: # update visited if this node has not been visited
      visited.add(newNode) 
   for neighbor in newNode.neighbors: # iterate over neighbors
      if neighbor not in visited: # check whether neighbors were visited
         stack.append(neighbor) # this node was not seen before, add it to To-Do list

In your case, it seems that your are not making the number of iterations dependent on whether there is an element left in the stack and your not getting the next element to visit from the stack since your not taking any elements out of it.在您的情况下,您似乎没有使迭代次数取决于堆栈中是否还有一个元素,并且您没有从堆栈中获取下一个要访问的元素,因为您没有从中取出任何元素。

You could try the following:您可以尝试以下方法:

def DFS(M, row, col, visited):
    rowNbr = [-1, -1, -1, 0, 0, 1, 1, 1]
    colNbr = [-1, 0, 1, -1, 1, -1, 0, 1]
    # initialize stack
    stack = [] 
    stack.append((row, col))
    while len(stack) != 0:
        row, col = stack.pop()
        if not visited[row, col]:
            visited[row, col] = 1
        # iterate over neighbors
        for k in range(8):
            if (isSafe(M, row + rowNbr[k], col + colNbr[k], visited)):
                row = row + rowNbr[k]
                col = col + colNbr[k]
                if not visited[row, col]:
                    stack.append((row, col))

This uses a tuple of (row, col) to mark positions and store them on the stack.这使用(row, col)的元组来标记位置并将它们存储在堆栈中。

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

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