1、编写算法,建立和输出基于邻接矩阵构造的图; 2、编写算法,建立和输出基于邻接表构造的图; 3、编写算法,基于邻接矩阵实现图的深度优先遍历; 4、编写算法,基于邻接表实现图的深度优先遍历; 5、编写算法,基
时间: 2024-03-23 08:43:24 浏览: 66
于邻接矩阵实现图的广度优先遍历; 6、编写算法,基于邻接表实现图的广度优先遍历。
对于问题1和2,建立图的算法主要涉及到邻接矩阵和邻接表的构建,其中邻接矩阵是以一个二维数组的形式存储图的结构,而邻接表则是通过链表的形式存储图的结构。具体的算法实现可以参考以下代码:
邻接矩阵构造图算法:
```python
def create_adjacency_matrix_graph(n, edges):
"""
:param n: 图中节点的个数
:param edges: 图中边的集合
:return: 邻接矩阵表示的图
"""
graph = [[0] * n for _ in range(n)]
for edge in edges:
graph[edge[0]][edge[1]] = 1
graph[edge[1]][edge[0]] = 1
return graph
```
邻接表构造图算法:
```python
class Node:
def __init__(self, val):
self.val = val
self.next = None
def create_adjacency_list_graph(n, edges):
"""
:param n: 图中节点的个数
:param edges: 图中边的集合
:return: 邻接表表示的图
"""
graph = [None] * n
for edge in edges:
node1 = Node(edge[1])
node2 = Node(edge[0])
node1.next = graph[edge[0]]
node2.next = graph[edge[1]]
graph[edge[0]] = node1
graph[edge[1]] = node2
return graph
```
对于问题3和4,深度优先遍历算法(DFS)的实现可以采用递归的方式,具体的实现可以参考以下代码:
邻接矩阵实现图的深度优先遍历算法:
```python
def dfs_adjacency_matrix(graph, visited, start):
"""
:param graph: 邻接矩阵表示的图
:param visited: 标记节点是否已访问的数组
:param start: 遍历的起始节点
"""
visited[start] = True
print(start, end=' ')
for i in range(len(graph)):
if graph[start][i] == 1 and not visited[i]:
dfs_adjacency_matrix(graph, visited, i)
```
邻接表实现图的深度优先遍历算法:
```python
def dfs_adjacency_list(graph, visited, start):
"""
:param graph: 邻接表表示的图
:param visited: 标记节点是否已访问的数组
:param start: 遍历的起始节点
"""
visited[start] = True
print(start, end=' ')
node = graph[start]
while node:
if not visited[node.val]:
dfs_adjacency_list(graph, visited, node.val)
node = node.next
```
对于问题5和6,广度优先遍历算法(BFS)的实现可以采用队列的方式,具体实现可以参考以下代码:
邻接矩阵实现图的广度优先遍历算法:
```python
from collections import deque
def bfs_adjacency_matrix(graph, visited, start):
"""
:param graph: 邻接矩阵表示的图
:param visited: 标记节点是否已访问的数组
:param start: 遍历的起始节点
"""
queue = deque([start])
visited[start] = True
while queue:
node = queue.popleft()
print(node, end=' ')
for i in range(len(graph)):
if graph[node][i] == 1 and not visited[i]:
visited[i] = True
queue.append(i)
```
邻接表实现图的广度优先遍历算法:
```python
from collections import deque
def bfs_adjacency_list(graph, visited, start):
"""
:param graph: 邻接表表示的图
:param visited: 标记节点是否已访问的数组
:param start: 遍历的起始节点
"""
queue = deque([start])
visited[start] = True
while queue:
node = queue.popleft()
print(node, end=' ')
next_node = graph[node]
while next_node:
if not visited[next_node.val]:
visited[next_node.val] = True
queue.append(next_node.val)
next_node = next_node.next
```
阅读全文