我正试图将递归代码转换为迭代代码,任务是找到网格中最大的区域(由1组成的连接单元)。任务是找到网格中最大的区域(由1组成的连接单元)。
代码参考了这里的内容。https:/www.geeksforgeeks.orgfind-length-largest-region-boolean-matrix我试过用堆栈和循环来代替递归,但没有效果。
这是我试过的代码,但它不能重现与递归方法相同的结果。
我已经用
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])
使用堆栈的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
在你的例子中,似乎你的迭代次数并不取决于堆栈中是否还有一个元素,而且由于你没有从堆栈中取出任何元素,所以你没有从堆栈中得到下一个要访问的元素。
你可以试试下面的方法。
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))
这使用了一个元组 (row, col)
来标记位置并将其存储在堆栈上。