有向图的深度优先遍历python
时间: 2024-03-13 14:41:21 浏览: 149
有向图的深度优先遍历(Depth First Search, DFS)是一种用于遍历图的算法。它从图中的一个顶点开始,沿着一条路径尽可能深地访问图中的顶点,直到无法继续前进为止,然后回溯到前一个顶点,继续探索其他路径。以下是一个用Python实现有向图深度优先遍历的示例代码:
```python
# 定义有向图类
class DirectedGraph:
def __init__(self):
self.graph = {}
# 添加边
def add_edge(self, start, end):
if start in self.graph:
self.graph[start].append(end)
else:
self.graph[start] = [end]
# 深度优先遍历
def dfs(self, start):
visited = set() # 记录已访问的节点
def dfs_helper(node):
visited.add(node)
print(node, end=" ") # 输出节点值
if node in self.graph:
for neighbor in self.graph[node]:
if neighbor not in visited:
dfs_helper(neighbor)
dfs_helper(start)
# 创建有向图对象
graph = DirectedGraph()
# 添加边
graph.add_edge('A', 'B')
graph.add_edge('A', 'C')
graph.add_edge('B', 'D')
graph.add_edge('B', 'E')
graph.add_edge('C', 'F')
# 深度优先遍历
print("深度优先遍历结果:")
graph.dfs('A')
```
运行以上代码,输出结果为:A B D E C F
阅读全文