带有矩阵的有向图Dijkstra算法python代码
时间: 2023-10-12 12:32:04 浏览: 120
以下是带有矩阵的有向图Dijkstra算法的Python代码实现:
```python
import numpy as np
def dijkstra(graph, start):
n = graph.shape[0]
visited = [False] * n
distances = [float('inf')] * n
distances[start] = 0
for _ in range(n):
u = np.argmin([distances[i] for i in range(n) if not visited[i]])
visited[u] = True
for v in range(n):
if graph[u][v] != 0 and not visited[v]:
new_distance = distances[u] + graph[u][v]
if new_distance < distances[v]:
distances[v] = new_distance
return distances
```
其中,`graph`是一个Numpy矩阵,表示有向图的邻接矩阵;`start`是起点的编号。该算法返回一个列表,表示起点到每个点的最短距离。
相关问题
python实现矩阵Dijkstra有向图算法代码
下面是Python实现矩阵Dijkstra有向图算法的代码:
```python
import sys
def dijkstra(graph, src):
"""
矩阵Dijkstra有向图算法
:param graph: 有向图
:param src: 源节点
:return: 距离列表
"""
n = len(graph)
dist = [sys.maxsize] * n # 起点到各个节点的距离列表
visited = [False] * n # 节点是否已访问的标记
dist[src] = 0 # 起点到起点的距离为0
for _ in range(n):
u = min_distance(dist, visited) # 未访问节点中距离最短的节点
visited[u] = True # 标记为已访问
# 更新未访问节点的距离
for v in range(n):
if graph[u][v] > 0 and not visited[v] and dist[v] > dist[u] + graph[u][v]:
dist[v] = dist[u] + graph[u][v]
return dist
def min_distance(dist, visited):
"""
从未访问节点中选择距离最短的节点
:param dist: 距离列表
:param visited: 是否已访问的标记
:return: 距离最短的节点
"""
min_dist = sys.maxsize
min_index = -1
for v in range(len(dist)):
if not visited[v] and dist[v] < min_dist:
min_dist = dist[v]
min_index = v
return min_index
```
其中,`graph`参数是一个二维矩阵,表示有向图的邻接矩阵,`src`参数是源节点的下标。函数返回的是距离列表,列表中的第`i`个元素表示从源节点到第`i`个节点的最短距离。
迪杰斯特拉算法 python代码实现有向图
迪杰斯特拉(Dijkstra's Algorithm)是一种用于寻找图中两点之间最短路径的算法,通常应用于带权重的有向图或无向图。以下是Python中使用邻接矩阵表示的有向图实现Dijkstra算法的一个简单示例:
```python
import heapq
def dijkstra(graph, start):
distances = {node: float('inf') for node in graph}
distances[start] = 0
queue = [(0, start)]
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
heapq.heappush(queue, (distance, neighbor))
return distances
# 示例:有向图的邻接矩阵表示,其中weights是从start到end的距离
graph = {
'A': {'B': 1, 'C': 4},
'B': {'A': 1, 'C': 2, 'D': 5},
'C': {'A': 4, 'B': 2, 'D': 1},
'D': {'B': 5, 'C': 1}
}
start = 'A'
shortest_distances = dijkstra(graph, start)
print("从{}到各个节点的最短距离: {}".format(start, shortest_distances))
阅读全文