图的邻接表创建、深度优先遍历和广度优先遍历代码实现,代码总汇
时间: 2023-06-21 13:09:26 浏览: 89
邻接表创建:
```python
class Graph:
def __init__(self, vertices):
self.V = vertices
self.graph = defaultdict(list)
def add_edge(self, u, v):
self.graph[u].append(v)
self.graph[v].append(u)
```
深度优先遍历:
```python
class Graph:
def __init__(self, vertices):
self.V = vertices
self.graph = defaultdict(list)
def add_edge(self, u, v):
self.graph[u].append(v)
self.graph[v].append(u)
def DFS(self, v, visited):
visited[v] = True
print(v, end=' ')
for i in self.graph[v]:
if visited[i] == False:
self.DFS(i, visited)
def DFS_traversal(self, v):
visited = [False] * (max(self.graph) + 1)
self.DFS(v, visited)
```
广度优先遍历:
```python
from collections import deque
class Graph:
def __init__(self, vertices):
self.V = vertices
self.graph = defaultdict(list)
def add_edge(self, u, v):
self.graph[u].append(v)
self.graph[v].append(u)
def BFS(self, v, visited):
queue = deque()
visited[v] = True
queue.append(v)
while queue:
s = queue.popleft()
print(s, end=' ')
for i in self.graph[s]:
if visited[i] == False:
visited[i] = True
queue.append(i)
def BFS_traversal(self, v):
visited = [False] * (max(self.graph) + 1)
self.BFS(v, visited)
```
以上是 Python 代码实现,使用 defaultdict 和 deque 两个工具类使得代码更加简洁和高效。
阅读全文