图的深度优先遍历python
时间: 2023-12-11 07:32:59 浏览: 70
以下是Python中图的深度优先遍历的实现方法:
```python
# 定义一个图类
class Graph:
def __init__(self, graph_dict=None):
if graph_dict is None:
graph_dict = {}
self.__graph_dict = graph_dict
# 添加节点
def add_node(self, node):
if node not in self.__graph_dict:
self.__graph_dict[node] = []
# 添加边
def add_edge(self, edge):
edge = set(edge)
(node1, node2) = tuple(edge)
if node1 in self.__graph_dict:
self.__graph_dict[node1].append(node2)
else:
self.__graph_dict[node1] = [node2]
# 深度优先遍历
def dfs(self, start, visited=None):
if visited is None:
visited = set()
visited.add(start)
print(start)
for next_node in self.__graph_dict[start]:
if next_node not in visited:
self.dfs(next_node, visited)
# 创建一个图实例
graph = Graph()
# 添加节点
graph.add_node('A')
graph.add_node('B')
graph.add_node('C')
graph.add_node('D')
graph.add_node('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
```
阅读全文