簡體   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