简体   繁体   English

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

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

I am beginner in DSA.I am student and am learn to solve graph problems.我是 DSA 的初学者。我是学生,正在学习解决图形问题。 In past experience i am traversing adjacency matrix graph by DFS and BFS but there is nodes are start by 0 to 5 like index but in this case nodes are starting from "A" to "Z" so i need help to solve the problems.在过去的经验中,我通过 DFS 和 BFS 遍历邻接矩阵图,但有些节点像索引一样从 0 到 5 开始,但在这种情况下,节点从“A”到“Z”开始,所以我需要帮助来解决问题。

below is code of graph and what i try for solving problem:-以下是图表代码以及我为解决问题所做的尝试:-

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()

I want to traverse adjacency matrix graph by DFS and BFS method:-我想通过 DFS 和 BFS 方法遍历邻接矩阵图:-

    def DFS(self):
        pass

    def BFS(self):
        pass

graphs.DFS()
graphs.BFS()

Your DFS and BFS methods do not have an entry point, the search should start in some vertex, so the first thing to do should be adding parameters for this.您的 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]}")

In the DFS case, we are simply traversing along the first encountered nodes.在 DFS 情况下,我们只是简单地遍历第一个遇到的节点。 For example from starting point "A", first encountered node will be "B".例如从起点“A”开始,第一个遇到的节点将是“B”。 For "B" it will be "D", and so on.对于“B”,它将是“D”,依此类推。 By tracing edges and nodes you can find out traversal as follows:通过跟踪边和节点,您可以找到遍历如下:

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

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

A->Z A->Z

And for the BFS, instead of traversing the first encountered nodes, the nodes are traversed in breadth, that is traversing all nodes at the current depth before moving on to the next depth.而对于 BFS,不是遍历第一个遇到的节点,而是遍历节点,即遍历当前深度的所有节点,然后再移动到下一个深度。 Again for the "A", the traversal can be as:同样对于“A”,遍历可以是:

Node "A" (this is first depth):节点“A”(这是第一个深度):

A->B A->B

A->C A->C

A->Z A->Z

Nodes at the second depth:第二深度的节点:

B->D B->D

C->E C->E

Nodes at the third depth:第三深度的节点:

D->G D->G

E->F E->F

Nodes at the fourth depth:第四个深度的节点:

F->G F->G

Since you do not store a mapping between nodes (letters in your example) and their indices, indices are obtained by searching through your node list using self.node.index .由于您不存储节点(示例中的字母)与其索引之间的映射,因此索引是通过使用self.node.index搜索节点列表来获得的。 It would be better if you use a map for such conversions.如果您使用 map 进行此类转换会更好。

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

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