图的邻接矩阵存储求个结点的度
时间: 2023-06-18 15:07:22 浏览: 58
对于一个图的邻接矩阵,求一个节点的度可以通过以下步骤实现:
1. 找到该节点在邻接矩阵中对应的行或列。
2. 统计该行或列中非零元素的数量,即为该节点的度。
以下是一个邻接矩阵的示例和求节点1的度的过程:
```
0 1 2 3
0 0 1 0 1
1 1 0 1 1
2 0 1 0 0
3 1 1 0 0
```
对应节点1的行为 `[1, 0, 1, 1]`,其中非零元素数量为 3,因此节点1的度为 3。
相关问题
python制作一个邻接矩阵并求邻接矩阵中节点的入度、出度和度
以下是制作邻接矩阵并求节点入度、出度和度的Python代码:
```python
n = int(input()) # 输入顶点数
matrix = [] # 存储邻接矩阵
for i in range(n):
row = list(map(int, input().split()))
matrix.append(row)
# 计算每个节点的入度、出度和度
for i in range(n):
in_degree = 0 # 入度
out_degree = 0 # 出度
degree = 0 # 度
for j in range(n):
if matrix[i][j] == 1:
out_degree += 1
if matrix[j][i] == 1:
in_degree += 1
degree = in_degree + out_degree
print("节点{}的入度为{},出度为{},度为{}".format(i+1, in_degree, out_degree, degree))
```
以上代码首先输入顶点数n,然后输入n行邻接矩阵,将邻接矩阵存储在一个二维列表matrix中。接着,对于每个节点,遍历邻接矩阵,计算其入度、出度和度,并输出结果。
实现有向图的邻接矩阵存储结构建立,使用图的非递归搜索算法,求出该有向图结点的度
邻接矩阵是一种表示图的数据结构,对于有向图而言,邻接矩阵可以采用以下方式实现:
1. 创建一个大小为n*n的二维数组,其中n为有向图中的节点数;
2. 对于有向边(i,j),邻接矩阵中第i行第j列的元素值为1,表示从节点i到节点j有一条有向边;
3. 如果有向边(i,j)不存在,则邻接矩阵中第i行第j列的元素值为0。
举个例子,对于如下有向图:
```
1 ------> 2 <------ 3
| | |
| | |
v v v
4 ------->5-------->6
```
其邻接矩阵可以表示为:
```
1 2 3 4 5 6
1 0 1 0 1 0 0
2 0 0 1 0 1 0
3 0 0 0 0 1 1
4 0 0 0 0 0 1
5 0 0 0 0 0 0
6 0 0 0 0 0 0
```
其中,第i行的元素之和即为第i个节点的出度,第i列的元素之和即为第i个节点的入度。
使用图的非递归搜索算法求出该有向图结点的度,可以采用BFS算法或DFS算法实现。下面以BFS算法为例:
```python
def bfs(adj_matrix, node):
queue = [node]
visited = set()
while queue:
cur_node = queue.pop(0)
if cur_node not in visited:
visited.add(cur_node)
for i in range(len(adj_matrix)):
if adj_matrix[cur_node][i] == 1:
queue.append(i)
return visited
# 计算节点的度
def get_degree(adj_matrix, node):
# 计算出度
out_degree = sum(adj_matrix[node])
# 计算入度
in_degree = len(bfs(adj_matrix.transpose(), node))
return out_degree, in_degree
# 示例
adj_matrix = [[0, 1, 0, 1, 0, 0],
[0, 0, 1, 0, 1, 0],
[0, 0, 0, 0, 1, 1],
[0, 0, 0, 0, 0, 1],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0]]
node = 2
out_degree, in_degree = get_degree(adj_matrix, node)
print("节点{}的出度为{},入度为{}".format(node, out_degree, in_degree))
```
输出结果为:
```
节点2的出度为1,入度为2
```
即节点2的出度为1,入度为2。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.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)