图的创建及遍历(DFS和BFS)PYTHON
时间: 2023-12-12 15:04:39 浏览: 129
好的,下面是用Python实现图的创建及遍历(DFS和BFS)的示例代码:
创建图(邻接表实现):
```python
class Graph:
def __init__(self, vertices):
self.vertices = vertices
self.adj_list = {vertex: [] for vertex in vertices}
def add_edge(self, u, v):
self.adj_list[u].append(v)
self.adj_list[v].append(u)
```
创建图(邻接矩阵实现):
```python
class Graph:
def __init__(self, vertices):
self.vertices = vertices
self.adj_matrix = [[0 for _ in range(len(vertices))] for _ in range(len(vertices))]
def add_edge(self, u, v):
self.adj_matrix[u][v] = 1
self.adj_matrix[v][u] = 1
```
DFS遍历:
```python
def dfs(graph, start):
visited = set()
stack = [start]
while stack:
vertex = stack.pop()
if vertex not in visited:
visited.add(vertex)
print(vertex)
for neighbor in graph.adj_list[vertex]:
if neighbor not in visited:
stack.append(neighbor)
```
BFS遍历:
```python
from collections import deque
def bfs(graph, start):
visited = set()
queue = deque([start])
while queue:
vertex = queue.popleft()
if vertex not in visited:
visited.add(vertex)
print(vertex)
for neighbor in graph.adj_list[vertex]:
if neighbor not in visited:
queue.append(neighbor)
```
注意:这是简单的示例代码,实际应用中可能需要考虑更多的情况,比如图中是否有环、是否有孤立节点等。
阅读全文