设计一个程序,采用交互方式建立一个网的邻接矩阵表示,并且: (1)分行输出该邻接矩阵; (2)求出各顶点的度并输出。
时间: 2024-05-13 20:15:34 浏览: 29
好的,我可以为您设计这个程序。以下是代码示例:
```python
# 定义一个函数,用于输入节点和边的数量,并且交互式输入每条边的起点和终点
def create_graph():
nodes = int(input("请输入节点数量:"))
edges = int(input("请输入边数量:"))
# 初始化邻接矩阵为全0
adjacency_matrix = [[0] * nodes for i in range(nodes)]
# 循环输入每条边,并在邻接矩阵中标记为1
for i in range(edges):
start_node = int(input("请输入边的起点:"))
end_node = int(input("请输入边的终点:"))
adjacency_matrix[start_node][end_node] = 1
adjacency_matrix[end_node][start_node] = 1
return adjacency_matrix
# 定义一个函数,用于输出邻接矩阵并计算每个节点的度
def print_matrix(adjacency_matrix):
degree = []
print("邻接矩阵:")
for row in adjacency_matrix:
degree.append(sum(row))
print(row)
print("节点度数:", degree)
# 调用函数创建图并输出邻接矩阵和节点度数
adjacency_matrix = create_graph()
print_matrix(adjacency_matrix)
```
运行程序后,您可以按照提示输入节点和边的数量,以及每条边的起点和终点,最后程序会输出邻接矩阵和节点度数。
相关推荐
![](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)
![](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)