繁体   English   中英

python中如何通过DFS和BFS方法遍历邻接矩阵图

[英]how to traverse adjacency matrix graph by DFS and BFS methods in python

我是 DSA 的初学者。我是学生,正在学习解决图形问题。 在过去的经验中,我通过 DFS 和 BFS 遍历邻接矩阵图,但有些节点像索引一样从 0 到 5 开始,但在这种情况下,节点从“A”到“Z”开始,所以我需要帮助来解决问题。

以下是图表代码以及我为解决问题所做的尝试:-

class Graph:
    node=[]
    graph=[]
    node_count=0

    def addNode(self,v):
        if v in self.node:
            print(f"{v} node is already present.")
        else:
            self.node_count +=1
            self.node.append(v)
            for n in self.graph:
                n.append(0)
            temp=[]
            for i in range(self.node_count):
                temp.append(0)
            self.graph.append(temp)

    
    def addEdges(self,v1,v2):
        if v1 not in self.node:
            print(f"{v1} is not in graph")
        elif v2 not in self.node:
            print(f"{v2} is not in graph")
        else:
            index1=self.node.index(v1)
            index2=self.node.index(v2)
            self.graph[index1][index2]=1

    def DFS(self):
        pass

    def BFS(self):
        pass

    def deleteNode(self,v):
        if v not in self.node:
            print(f"{v} is not present in the graph.")
        else:
            index1=self.node.index(v)
            self.node_count -=1
            self.node.remove(v)
            self.graph.pop(index1)
            for i in self.graph:
                i.pop(index1)

    def deleteEdges(self,v1,v2):
        if v1 not in self.node:
            print(f"{v1} is not in graph")
        elif v2 not in self.node:
            print(f"{v2} is not in graph")
        else:
            index1=self.node.index(v1)
            index2=self.node.index(v2)
            self.graph[index1][index2]=0



    def print_graph(self):
        for i in range(self.node_count):
            for j in range(self.node_count):
                print(self.graph[i][j],end=" ")
            print()

    



graphs=Graph()
graphs.addNode("A")
graphs.addNode("B")
graphs.addNode("C")
graphs.addNode("D")
graphs.addNode("E")
graphs.addNode("F")
graphs.addNode("G")
graphs.addNode("Z")
print(graphs.graph)
graphs.addEdges("A","B")
graphs.addEdges("A","C")
graphs.addEdges("B","D")
graphs.addEdges("C","E")
graphs.addEdges("E","F")
graphs.addEdges("D","G")
graphs.addEdges("F","G")
graphs.addEdges("A","Z")

graphs.DFS()
graphs.BFS()

print(graphs.node)
graphs.print_graph()

graphs.deleteNode("G")

print("AFTER DELETE")
graphs.print_graph()
print(graphs.node)

graphs.deleteEdges("E","F")

print("AFTER DELETE EDGE")
graphs.print_graph()

我想通过 DFS 和 BFS 方法遍历邻接矩阵图:-

    def DFS(self):
        pass

    def BFS(self):
        pass

graphs.DFS()
graphs.BFS()

您的 DFS 和 BFS 方法没有入口点,搜索应该从某个顶点开始,所以首先要做的是为此添加参数。

def DFS(self, start):
    start_idx = self.node.index(start)
    new_line = True  # for better visualization
    for i in range(self.node_count):
      if self.graph[start_idx][i]:
        new_line = False
        print(f"{start}->{self.node[i]}", end=" ")
        self.DFS(self.node[i])
    if new_line:
      print()


def BFS(self, start):
  que = queue.Queue()
  start_idx = self.node.index(start)
  que.put(start_idx)
  while not que.empty():
    curr_vertex = que.get()
    for i in range(self.node_count):
      if self.graph[curr_vertex][i]:
        que.put(i)
        print(f"{self.node[curr_vertex]}->{self.node[i]}")

在 DFS 情况下,我们只是简单地遍历第一个遇到的节点。 例如从起点“A”开始,第一个遇到的节点将是“B”。 对于“B”,它将是“D”,依此类推。 通过跟踪边和节点,您可以找到遍历如下:

A->B B->D D->G

A->C C->E E->F F->G

A->Z

而对于 BFS,不是遍历第一个遇到的节点,而是遍历节点,即遍历当前深度的所有节点,然后再移动到下一个深度。 同样对于“A”,遍历可以是:

节点“A”(这是第一个深度):

A->B

A->C

A->Z

第二深度的节点:

B->D

C->E

第三深度的节点:

D->G

E->F

第四个深度的节点:

F->G

由于您不存储节点(示例中的字母)与其索引之间的映射,因此索引是通过使用self.node.index搜索节点列表来获得的。 如果您使用 map 进行此类转换会更好。

暂无
暂无

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

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