python 有向非连通图的dfs、bfs
时间: 2024-03-07 09:47:14 浏览: 148
是的,Python可以使用DFS和BFS算法遍历有向非连通图。下面是两种算法的示例代码:
DFS算法:
```python
def dfs(graph, start, visited=set()):
visited.add(start)
print(start)
for neighbor in graph[start]:
if neighbor not in visited:
dfs(graph, neighbor, visited)
# 示例代码
graph = {0: [1, 2], 1: [3], 2: [3], 3: [4], 4: []}
dfs(graph, 0)
```
BFS算法:
```python
from collections import deque
def bfs(graph, start):
visited = set()
queue = deque([start])
visited.add(start)
while queue:
node = queue.popleft()
print(node)
for neighbor in graph[node]:
if neighbor not in visited:
visited.add(neighbor)
queue.append(neighbor)
# 示例代码
graph = {0: [1, 2], 1: [3], 2: [3], 3: [4], 4: []}
bfs(graph, 0)
```
需要注意的是,这里的图是以Python字典的形式表示的,其中键表示节点,值表示与该节点相邻的节点列表。在实际应用中,可以根据具体情况自行修改。
阅读全文