无线传感网络课程作业 1
仅供参考-如有需要可订阅专栏
- 题目
有如下网络图:
abc三个数以a=3,b=1,c=1为例
- 运行环境:anaconda3环境管理工具,Python 3.9.12,Windows 10 22H2
- 算法实现原理流程
i).程序包括两个函数:dijkstra和shortest_path。 ii). dijkstra函数有一个图(Graph)和一个起点作为输入。首先将所有节点的距离初始化为无穷大,然后将起点的距离设为0。接下来,它使用一个优先队列来存储未处理的节点,并按照距离从小到大的顺序取出节点。对于每个取出的节点,更新与该节点相邻的节点的距离。最后,返回从起点到其他所有节点的最短距离以及前面的节点。 iii).shortest_path函数以一个图、起点和终点作为输入,首先调用dijkstra函数来计算从起点到其他所有节点的最短距离和前面的节点。然后使用前驱节点来构造从终点到起点的最短路径。最后返回从起点到终点的最短距离和最短路径。 |
- 运行结果,输出了最短路径和经过的节点。代码见附录1
5.结果验证
为了检验代码的正确性,使用Matlab封装的dijkstra函数计算最短路径,代码见附录2
可见自己的代码和封装函数结果一致,计算正确。
附录一:编写的Dijkstra算法源代码 |
import heapq def dijkstra(graph, start): distances = {node: float('inf') for node in graph} distances[start] = 0 queue = [(0, start)] previous_nodes = {node: None for node in graph} while queue: # 取出距离起点最近的节点 current_distance, current_node = heapq.heappop(queue) # 如果该节点已经被处理过,则跳过 if current_distance > distances[current_node]: continue # 更新与该节点相邻的节点的距离 for neighbor, weight in graph[current_node].items(): distance = current_distance + weight if distance < distances[neighbor]: distances[neighbor] = distance previous_nodes[neighbor] = current_node heapq.heappush(queue, (distance, neighbor)) return distances, previous_nodes def shortest_path(graph, start, end): distances, previous_nodes = dijkstra(graph, start) path = [] node = end while node != start: path.append(node) node = previous_nodes[node] path.append(start) path.reverse() return distances[end], path graph = { '1': {'2': 1, '4': 3, '5': 5}, '2': {'1': 1, '3': 3, '4': 1, '6': 1}, '3': {'2': 3, '6': 1}, '4': {'1': 3, '2': 1, '5': 2, '6': 1}, '5': {'1': 5, '4': 2, '6': 1}, '6': {'2': 1, '3': 1, '4': 1, '5': 1} } start_node = "1" end_nodes = ["2", "3", "4", "5", "6"] for end_node in end_nodes: distances, path = shortest_path(graph=graph,start=start_node,end=end_node) print(f"节点 {end_node}到结点{start_node}最短路径为{distances},经过的结点为为 {path}") |
附录二:验证结果的正确性 |
s = [1 1 1 2 2 2 3 4 4 5]; t = [2 4 5 3 4 6 6 5 6 6]; w = [1 3 5 3 1 1 1 2 1 1]; G = graph(s,t,w); plot(G, 'EdgeLabel', G.Edges.Weight, 'linewidth', 2) set( gca, 'XTick', [], 'YTick', [] ); % ÔÚͼÖиßÁÁÎÒÃǵÄ×î¶Ì·¾¶ myplot = plot(G, 'EdgeLabel', G.Edges.Weight, 'linewidth', 2); %Ê×ÏȽ«Í¼¸³¸øÒ»¸ö±äÁ¿ % Çó³öÈÎÒâÁ½µãµÄ×î¶Ì·¾¶¾ØÕó D = distances(G) ; distance=[0,0,0,0,0]; distance(1)=D(2,1); % 1 -> 2µÄ×î¶Ì·¾¶ distance(2)=D(3,1); distance(3)=D(4,1); distance(4)=D(5,1); distance(5)=D(6,1); distance |