扩展节点。在这种情况下它是如何工作的?

时间:2021-07-04 05:50:32

标签: python graph depth-first-search

enter image description here

我有一个来自上图中的输入矩阵如下 [i, j] = A>0 如果从节点 i 到节点 j 存在权重 A 的链接,否则 [i, j] = 0。

0 4 3 0 0 0 0
4 0 0 0 12 5 0
3 0 0 7 10 0 0
0 0 7 0 2 0 0
0 12 10 2 0 0 5
0 5 0 0 0 0 16
0 0 0 0 5 16 0

起始节点(self.source)为0或顶点a,目的节点为6或顶点z

这个案例的结果是:

  • 扩展节点:0 1 4 2 3 (6) | a b e c d z
  • 返回路径:0 1 4 6 | a b e z

返回路径正确,但我的输出扩展节点错误:0 1 4 | a b e

我哪里做错了?

我的代码:

def DFS(self):

    explored = []
    frontier = deque()
    frontier.append([self.source])

    temp = deque()

    while True:            
        if len(frontier) == 0:
            self.expanded = explored
            return

        temp.clear()
        path = frontier.popleft()
        node = path[-1]
        explored.append(node)

        for i, s in enumerate(self.matrix[node]):
            if s != 0:
                if i not in explored:
                    newPath = list(path)
                    newPath.append(i)
                    
                    if i == self.des:
                        self.returnPath = newPath[::-1]
                        self.expanded = explored
                        return
                    else:
                        temp.append(newPath)
        temp += frontier
        frontier = temp.copy()

0 个答案:

没有答案
相关问题