完成图的创建(邻接矩阵或邻接表实现)及深度或广度优先遍历;输出顶点信息、邻接矩阵或邻接表、遍历序列;
时间: 2024-06-13 22:09:07 浏览: 107
以下是使用邻接矩阵实现图的创建和深度优先遍历的Python代码:
```python
class Graph:
def __init__(self, vertices):
self.V = vertices
self.graph = [[0] * self.V for _ in range(self.V)]
def add_edge(self, u, v):
self.graph[u][v] = 1
self.graph[v][u] = 1
def DFS(self, v, visited):
visited[v] = True
print(v, end=' ')
for i in range(self.V):
if self.graph[v][i] == 1 and not visited[i]:
self.DFS(i, visited)
def DFS_traversal(self, start):
visited = [False] * self.V
self.DFS(start, visited)
```
其中,`Graph`类表示一个图,`__init__`方法初始化图的顶点数和邻接矩阵,`add_edge`方法添加边,`DFS`方法实现深度优先遍历,`DFS_traversal`方法调用`DFS`方法进行遍历。
以下是使用邻接表实现图的创建和广度优先遍历的Python代码:
```python
from collections import defaultdict, deque
class Graph:
def __init__(self):
self.graph = defaultdict(list)
def add_edge(self, u, v):
self.graph[u].append(v)
self.graph[v].append(u)
def BFS_traversal(self, start):
visited = [False] * len(self.graph)
queue = deque([start])
visited[start] = True
while queue:
v = queue.popleft()
print(v, end=' ')
for i in self.graph[v]:
if not visited[i]:
visited[i] = True
queue.append(i)
```
其中,`Graph`类表示一个图,`__init__`方法初始化邻接表,`add_edge`方法添加边,`BFS_traver
阅读全文