python读取邻接矩阵txt文件计算最短路径并输出
时间: 2023-10-25 19:16:08 浏览: 130
要读取邻接矩阵txt文件,你可以使用Python内置的文件读写功能,具体步骤如下:
1. 打开文件并读取邻接矩阵
```python
with open('adj_matrix.txt', 'r') as f:
adj_matrix = []
for line in f.readlines():
row = list(map(int, line.strip().split()))
adj_matrix.append(row)
```
其中,`adj_matrix.txt`为邻接矩阵的文本文件名,假设每行用空格分隔,每个元素为整数。
2. 计算最短路径
你可以使用Dijkstra算法或者Floyd算法来计算最短路径。这里以Dijkstra算法为例:
```python
import heapq
def dijkstra(adj_matrix, start):
n = len(adj_matrix)
dist = [float('inf')] * n
dist[start] = 0
visited = set()
heap = [(0, start)]
while heap:
(d, v) = heapq.heappop(heap)
if v in visited:
continue
visited.add(v)
for w in range(n):
if adj_matrix[v][w] != 0 and w not in visited:
if dist[v] + adj_matrix[v][w] < dist[w]:
dist[w] = dist[v] + adj_matrix[v][w]
heapq.heappush(heap, (dist[w], w))
return dist
```
其中,`adj_matrix`为邻接矩阵,`start`为起点。函数返回一个列表,表示起点到各个点的最短距离。
3. 输出结果
最后,你可以将最短路径输出到文件中,或者直接打印出来。
```python
dist = dijkstra(adj_matrix, 0)
with open('result.txt', 'w') as f:
for i, d in enumerate(dist):
f.write(f'{i}: {d}\n')
```
其中,`result.txt`为结果文件名。这里将起点设为0,将结果输出到文件中。
完整代码:
```python
import heapq
def dijkstra(adj_matrix, start):
n = len(adj_matrix)
dist = [float('inf')] * n
dist[start] = 0
visited = set()
heap = [(0, start)]
while heap:
(d, v) = heapq.heappop(heap)
if v in visited:
continue
visited.add(v)
for w in range(n):
if adj_matrix[v][w] != 0 and w not in visited:
if dist[v] + adj_matrix[v][w] < dist[w]:
dist[w] = dist[v] + adj_matrix[v][w]
heapq.heappush(heap, (dist[w], w))
return dist
with open('adj_matrix.txt', 'r') as f:
adj_matrix = []
for line in f.readlines():
row = list(map(int, line.strip().split()))
adj_matrix.append(row)
dist = dijkstra(adj_matrix, 0)
with open('result.txt', 'w') as f:
for i, d in enumerate(dist):
f.write(f'{i}: {d}\n')
```
阅读全文