数据结构之图:用图解决案例,Python代码实现——24
生活随笔
收集整理的這篇文章主要介紹了
数据结构之图:用图解决案例,Python代码实现——24
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
用圖解決暢通工程案例與途徑查找
代碼中需要引入的類方法代碼鏈接:
暢通工程-續
介紹
- 案例和之前并查集中實現的一樣,但問題略有改動,需要判斷9-10城市是否相通,9-8城市是否相通:
使用圖解決次案例:
數據集
traffic.txt
20 7 0 1 6 9 3 8 5 11 2 12 6 10 4 8Python代碼實現
from Structure.graph.Undigraph import Undigraph from Structure.graph.DepthFirstSearch import DepthFirstSearch from Structure.graph.BreadthFirstSearch import BreadthFirstSearchwith open('../traffic.txt', 'r') as f:total = int(f.readline())UG = Undigraph(total)connected_nums = int(f.readline())for i in range(connected_nums):road = f.readline().split()UG.add_edge(int(road[0]), int(road[1]))city1 = 9city2 = 8city3 = 10print(f"----------------DFS test-----------------------")DFS = DepthFirstSearch(UG, city1)print(f"Is city[{city1}] connected with city[{city2}]? {DFS.is_marked(city2)}")print(f"Is city[{city1}] connected with city[{city3}]? {DFS.is_marked(city3)}")print(f"----------------BFS test-----------------------")BFS = BreadthFirstSearch(UG, city1)print(f"Is city[{city1}] connected with city[{city2}]? {BFS.is_marked(city2)}")print(f"Is city[{city1}] connected with city[{city3}]? {BFS.is_marked(city3)}")運行結果
----------------DFS test----------------------- Is city[9] connected with city[8]? False Is city[9] connected with city[10]? True ----------------BFS test----------------------- Is city[9] connected with city[8]? False Is city[9] connected with city[10]? True9通過6和10相連,9和8不是相通的
traffic.txt:
圖的路徑查找
引入
- 在實際生活中,地圖是我們經常使用的一種工具,通常我們會用它進行導航,輸入一個出發城市,輸入-個目的地城市,就可以把路線規劃好,而在規劃好的這個路線上,會路過很多中間的城市。這類問題翻譯成專業問題就是:從s頂點到頂點是否存在一條路徑 ?如果存在,請找出這條路徑。
在這里我們使用的是無向圖,只找出一條能夠連通的道路即可,后續學習了加權路徑之后在尋找指定的路徑
實現步驟
- 我們實現路徑查找,最基本的操作還是遍歷或搜索圖,所以,我們的實現暫且基于深度優先搜索來完成。其搜索的過程是比較簡單的。我們添加了edgeTo[]整型數組,這個整型數組會記錄從每個頂點回到起點s的路徑。如果我們把頂點設定為0 ,那么它的搜索可以表示為下圖:
屬性與方法設計
DFS.txt:
6 8 0 2 0 1 2 1 2 3 2 4 3 5 3 4 0 5Python代碼實現
from Structure.graph.Undigraph import Undigraphclass DepthFirstSearch:def __init__(self, graph, start):self.UD = graphself.start = startself.marked = [False for _ in range(self.UD.vertex)]self.edgeTo = [None for _ in range(self.UD.vertex)]self.dfs(start)def dfs(self, s):self.marked[s] = Trueedges = self.UD.get_edges_of(s)for e in edges:if not self.marked[e]:self.edgeTo[e] = sself.dfs(e)def has_path_to(self, v):return self.marked[v]def path_to(self, v):if not self.has_path_to(v):returnpath = [v]while self.edgeTo[v] != self.start:v = self.edgeTo[v]path.insert(0, v)path.insert(0, self.start)return pathif __name__ == '__main__':with open('../DFP.txt', 'r') as f:vertices = int(f.readline())UG = Undigraph(vertices)nums = int(f.readline())for i in range(nums):x, y = f.readline().split()UG.add_edge(int(x), int(y))DFP = DepthFirstSearch(UG, 0)print(DFP.path_to(5))運行結果
[0, 2, 3, 5]順序不是唯一,跟建立邊的順序,以及設置的優先順序也有關系,后續會學習到加了權重的邊的圖,則可以解決最短路徑問題,引入的代碼地址請回到頂部參考
總結
以上是生活随笔為你收集整理的数据结构之图:用图解决案例,Python代码实现——24的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【Pytorch神经网络实战案例】01
- 下一篇: OpenCV_11 轮廓检测:图像的轮廓