日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

Python使用鄰接矩陣實現圖及Dijkstra算法問題_python

作者:科恩兄弟 ? 更新時間: 2023-01-17 編程語言

使用鄰接矩陣實現圖及Dijkstra算法

# 鄰接矩陣實現無向圖 Dijkstra算法
inf = float("inf")


class Graph():
    def __init__(self, n):
        self.vertexn = n
        self.gType = 0
        self.vertexes = [inf]*n
        self.arcs = [self.vertexes*n]  # 鄰接矩陣
        self.visited = [False]*n  # 用于深度遍歷記錄結點的訪問情況

    def addvertex(self, v, i):
        self.vertexes[i] = v

    def addarcs(self, row, column, weight):
        self.arcs[row][column] = weight

    # 深度優先遍歷
    def DFS(self, i):
        j = 0
        print("vertex:{}".format(self.vertexes[i]), end=" ")  # 先打印訪問到的節點
        self.visited[i] = True
        while j < self.vertexn:
            if (self.arcs[i][j] != inf) and (not self.visited[j]):
                print(self.arcs[i][j], end=" ")
                self.DFS(j)
            j += 1

    # 廣度優先遍歷
    def BFS(self, k):
        self.visited = [False]*self.vertexn  # 訪問性重置
        q = []
        print("vertex:{}".format(self.vertexes[k]), end=" ")
        self.visited[k] = True
        q.append(k)
        while q != []:
            i = q.pop(0)
            for j in range(self.vertexn):
                if(self.arcs[i][j] != inf) and (not self.visited[j]):
                    print(self.arcs[i][j], end=" ")  # 父節點與子節點的距離
                    print("vertex:{}".format(self.vertexes[j]), end=" ")
                    self.visited[j] = True
                    q.append(j)

    # 最短路徑算法-Dijkstra 輸入點v0,找到所有點到v0的最短距離
    def Dijkstra(self, v0):
        # 初始化操作
        D = [inf]*self.vertexn  # 用于存放從頂點v0到v的最短路徑長度
        path = [None]*self.vertexn  # 用于存放從頂點v0到v的路徑
        final = [None]*self.vertexn  # 表示從v0到v的最短路徑是否找到最短路徑
        for i in range(self.vertexn):
            final[i] = False
            D[i] = self.arcs[v0][i]
            path[i] = ""  # 路徑先置空
            if D[i] < inf:
                path[i] = self.vertexes[i]  # 如果v0直接連到第i點,則路徑直接改為i
        D[v0] = 0
        final[v0] = True
        ###
        for i in range(1, self.vertexn):
            min = inf  # 找到離v0最近的頂點
            for k in range(self.vertexn):
                if(not final[k]) and (D[k] < min):
                    v = k
                    min = D[k]
            final[v] = True  # 最近的點找到,加入到已得最短路徑集合S中 此后的min將在處S以外的vertex中產生
            for k in range(self.vertexn):
                if(not final[k]) and (min+self.arcs[v][k] < D[k]):
                    # 如果最短的距離(v0-v)加上v到k的距離小于現存v0到k的距離
                    D[k] = min+self.arcs[v][k]
                    path[k] = path[v]+","+self.vertexes[k]
        return D, path


if __name__ == "__main__":
    g = Graph(5)
    g.vertexes = ["A", "B", "C", "D", "E"]
    g.arcs = [[inf, 60, 80, 30, inf], [60, inf, 40, 75, inf], [
        80, 40, inf, inf, 35], [30, 75, inf, inf, 45], [inf, inf, 35, 45, inf]]

    print("深度優先遍歷:")
    g.DFS(0)
    print("\n廣度優先遍歷:")
    g.BFS(0)
    print()

    print("Dijkstra搜索點到圖中各點的最短路徑:")
    D, path = g.Dijkstra(0)
    print(D)
    print(path)

將鄰接矩陣輸出成圖

利用networkx,numpy,matplotlib,將鄰接矩陣輸出為圖形。

1,自身確定一個鄰接矩陣,然后通過循環的方式添加變,然后輸出圖像

import networkx as nx
import matplotlib.pyplot as plt
import numpy as np
 
G = nx.Graph()
Matrix = np.array(
    [
        [0, 1, 1, 1, 1, 1, 0, 0],  # a
        [0, 0, 1, 0, 1, 0, 0, 0],  # b
        [0, 0, 0, 1, 0, 0, 0, 0],  # c
        [0, 0, 0, 0, 1, 0, 0, 0],  # d
        [0, 0, 0, 0, 0, 1, 0, 0],  # e
        [0, 0, 1, 0, 0, 0, 1, 1],  # f
        [0, 0, 0, 0, 0, 1, 0, 1],  # g
        [0, 0, 0, 0, 0, 1, 1, 0]  # h
    ]
)
for i in range(len(Matrix)):
    for j in range(len(Matrix)):
        G.add_edge(i, j)
 
nx.draw(G)
plt.show()
 

2,有向圖

G = nx.DiGraph()
G.add_node(1)
G.add_node(2)
G.add_nodes_from([3, 4, 5, 6])
G.add_cycle([1, 2, 3, 4])
G.add_edge(1, 3)
G.add_edges_from([(3, 5), (3, 6), (6, 7)])
nx.draw(G)
# plt.savefig("youxiangtu.png")
plt.show()

3,5節點完全圖

G = nx.complete_graph(5)
nx.draw(G)
plt.savefig("8nodes.png")
plt.show()

4,無向圖

G = nx.Graph()
G.add_node(1)
G.add_node(2)
G.add_nodes_from([3, 4, 5, 6])
G.add_cycle([1, 2, 3, 4])
G.add_edge(1, 3)
G.add_edges_from([(3, 5), (3, 6), (6, 7)])
nx.draw(G)
# plt.savefig("wuxiangtu.png")
plt.show()

5,顏色節點圖

G = nx.Graph()
G.add_edges_from([(1, 2), (1, 3), (1, 4), (1, 5), (4, 5), (4, 6), (5, 6)])
pos = nx.spring_layout(G)
 
colors = [1, 2, 3, 4, 5, 6]
nx.draw_networkx_nodes(G, pos, node_color=colors)
nx.draw_networkx_edges(G, pos)
 
plt.axis('off')
# plt.savefig("color_nodes.png")
plt.show()

將圖轉化為鄰接矩陣,再將鄰接矩陣轉化為圖,還有圖的集合表示,鄰接矩陣表示,圖形表示,這三種表現形式互相轉化的問題是一個值得學習的地方。

總結

原文鏈接:https://blog.csdn.net/Joker_Lord/article/details/103396854

欄目分類
最近更新