python读取txt文件存为邻接矩阵
时间: 2023-09-10 20:05:43 浏览: 159
假设你的txt文件中存储的是一个无向图的边信息,每行两个数字表示一条边的两个端点,那么你可以通过以下代码读取txt文件并生成邻接矩阵:
```python
import numpy as np
# 读取txt文件
with open('graph.txt', 'r') as f:
edges = f.readlines()
# 构建邻接矩阵
n = len(edges) # 图中边的数量
adj_matrix = np.zeros((n, n)) # 初始化邻接矩阵
for i in range(n):
edge = edges[i].strip().split() # 去掉空格并分割每行的两个数字
u, v = int(edge[0]), int(edge[1])
adj_matrix[u][v] = 1 # 标记边的两个端点
adj_matrix[v][u] = 1 # 无向图需要标记双向边
print(adj_matrix)
```
其中,`graph.txt`是存储无向图边信息的txt文件名。这段代码读取txt文件并生成一个n x n的邻接矩阵,其中n是边的数量。邻接矩阵中的元素`adj_matrix[i][j]`表示第i个节点和第j个节点是否有一条边相连,1表示有,0表示没有。注意,在无向图中,邻接矩阵是对称的,即`adj_matrix[i][j] = adj_matrix[j][i]`。
相关问题
python读取邻接矩阵txt文件计算拉普拉斯矩阵并输出
假设邻接矩阵txt文件的格式如下:
```
0 1 0 1
1 0 1 1
0 1 0 0
1 1 0 0
```
其中每行表示一个节点的邻居节点情况,1表示有边相连,0表示没有边相连。
下面是一个Python程序读取该文件,计算拉普拉斯矩阵并输出的示例代码:
```python
import numpy as np
# 读取邻接矩阵txt文件
adj_matrix = np.loadtxt('adj_matrix.txt', dtype=np.int)
# 计算度矩阵
degree_matrix = np.diag(np.sum(adj_matrix, axis=1))
# 计算拉普拉斯矩阵
laplacian_matrix = degree_matrix - adj_matrix
# 输出拉普拉斯矩阵
print(laplacian_matrix)
```
输出结果为:
```
[[ 2 -1 0 -1]
[-1 3 -1 -1]
[ 0 -1 1 0]
[-1 -1 0 2]]
```
其中,对角线上的元素表示每个节点的度数,非对角线上的元素表示节点之间的边数。
python读取邻接矩阵txt文件计算最短路径并输出
要读取邻接矩阵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')
```
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)