有向图邻接矩阵建图和度数输出
时间: 2023-12-21 21:31:05 浏览: 159
有向图的邻接矩阵.。。
5星 · 资源好评率100%
以下是有向图邻接矩阵建图和度数输出的示例代码:
```python
class Graph:
def __init__(self, num_vertices):
self.num_vertices = num_vertices
self.adj_matrix = [[0] * num_vertices for _ in range(num_vertices)]
def add_edge(self, start_vertex, end_vertex):
self.adj_matrix[start_vertex][end_vertex] = 1
def get_indegree(self, vertex):
indegree = 0
for i in range(self.num_vertices):
if self.adj_matrix[i][vertex] == 1:
indegree += 1
return indegree
def get_outdegree(self, vertex):
outdegree = 0
for i in range(self.num_vertices):
if self.adj_matrix[vertex][i] == 1:
outdegree += 1
return outdegree
# 创建一个有向图
g = Graph(5)
g.add_edge(0, 1)
g.add_edge(0, 2)
g.add_edge(1, 3)
g.add_edge(2,3)
g.add_edge(3, 4)
# 输出每个顶点的入度和出度
for i in range(g.num_vertices):
print("Vertex", i)
print("Indegree:", g.get_indegree(i))
print("Outdegree:", g.get_outdegree(i))
print()
```
输出结果:
```
Vertex 0
Indegree: 0
Outdegree: 2
Vertex 1
Indegree: 1
Outdegree: 1
Vertex 2
Indegree: 1
Outdegree: 1
Vertex 3
Indegree: 2
Outdegree: 1
Vertex 4
Indegree: 1
Outdegree: 0
```
阅读全文