图的两种存储结构实现代码和(1)对以邻接矩阵为存储结构的图进行 DFS和 BFS遍历,输出以某顶点为起始点的DFS和BFS序列。 (2)对以邻接表为存储结构的图进行DFS和BFS遍历,输出以某顶点为起始点的DFS和BFS序列。
时间: 2024-05-07 07:17:32 浏览: 128
好的,首先回答您的问题:
1. 邻接矩阵和邻接表的存储结构实现代码:
邻接矩阵的实现代码:
```python
class Graph:
def __init__(self, vertex_num):
self.vertex_num = vertex_num
self.graph = [[0] * vertex_num for _ in range(vertex_num)]
def add_edge(self, u, v):
self.graph[u][v] = 1
self.graph[v][u] = 1
def dfs(self, start):
visited = [False] * self.vertex_num
self._dfs(start, visited)
def _dfs(self, cur, visited):
visited[cur] = True
print(cur, end=' ')
for i in range(self.vertex_num):
if self.graph[cur][i] == 1 and not visited[i]:
self._dfs(i, visited)
def bfs(self, start):
visited = [False] * self.vertex_num
queue = [start]
visited[start] = True
while queue:
node = queue.pop(0)
print(node, end=' ')
for i in range(self.vertex_num):
if self.graph[node][i] == 1 and not visited[i]:
visited[i] = True
queue.append(i)
g = Graph(5)
g.add_edge(0, 1)
g.add_edge(0, 2)
g.add_edge(1, 3)
g.add_edge(2, 4)
g.dfs(0)
print()
g.bfs(0)
```
邻接表的实现代码:
```python
class Graph:
def __init__(self, vertex_num):
self.vertex_num = vertex_num
self.graph = [[] for _ in range(vertex_num)]
def add_edge(self, u, v):
self.graph[u].append(v)
self.graph[v].append(u)
def dfs(self, start):
visited = [False] * self.vertex_num
self._dfs(start, visited)
def _dfs(self, cur, visited):
visited[cur] = True
print(cur, end=' ')
for i in self.graph[cur]:
if not visited[i]:
self._dfs(i, visited)
def bfs(self, start):
visited = [False] * self.vertex_num
queue = [start]
visited[start] = True
while queue:
node = queue.pop(0)
print(node, end=' ')
for i in self.graph[node]:
if not visited[i]:
visited[i] = True
queue.append(i)
g = Graph(5)
g.add_edge(0, 1)
g.add_edge(0, 2)
g.add_edge(1, 3)
g.add_edge(2, 4)
g.dfs(0)
print()
g.bfs(0)
```
2. 以某个顶点为起始点的DFS和BFS序列的输出
假设我们以顶点0为起始点,则输出的DFS序列为:0 1 3 2 4,输出的BFS序列为:0 1 2 3 4
希望这个答案能够满足您的需求,如果还有其他的问题,欢迎继续提出哦~
阅读全文