python实现图的深度优先搜索
时间: 2023-11-22 15:49:17 浏览: 78
以下是Python实现图的深度优先搜索的示例代码:
```python
# 定义图的类
class Graph:
def __init__(self, graph_dict=None):
if graph_dict is None:
graph_dict = {}
self.__graph_dict = graph_dict
# 添加顶点
def add_vertex(self, vertex):
if vertex not in self.__graph_dict:
self.__graph_dict[vertex] = []
# 添加边
def add_edge(self, edge):
edge = set(edge)
(vertex1, vertex2) = tuple(edge)
if vertex1 in self.__graph_dict:
self.__graph_dict[vertex1].append(vertex2)
else:
self.__graph_dict[vertex1] = [vertex2]
# 深度优先搜索
def dfs(self, start_vertex, visited=None):
if visited is None:
visited = set()
visited.add(start_vertex)
print(start_vertex)
for next_vertex in self.__graph_dict[start_vertex] - visited:
self.dfs(next_vertex, visited)
return visited
# 创建图的实例
graph = Graph()
# 添加顶点和边
graph.add_vertex('A')
graph.add_vertex('B')
graph.add_vertex('C')
graph.add_vertex('D')
graph.add_vertex('E')
graph.add_edge({'A', 'B'})
graph.add_edge({'B', 'C'})
graph.add_edge({'C', 'D'})
graph.add_edge({'D', 'E'})
graph.add_edge({'E', 'A'})
# 进行深度优先搜索
graph.dfs('A')
```
输出结果为:
```
A
B
C
D
E
```
阅读全文