邻接矩阵的DFS和BFS算法代码简单明了
时间: 2023-12-11 14:32:41 浏览: 96
以下是邻接矩阵的DFS和BFS算法的Python代码:
DFS算法:
```python
def DFS(visited, graph, node):
if node not in visited:
print(node, end=" ")
visited.add(node)
for neighbor in range(len(graph[node])):
if graph[node][neighbor] == 1:
DFS(visited, graph, neighbor)
# 示例代码
graph = [[0, 1, 1, 0, 0],
[1, 0, 0, 1, 1],
[1, 0, 0, 1, 0],
[0, 1, 1, 0, 1],
[0, 1, 0, 1, 0]]
visited = set() # 用集合来存储已经访问过的节点
print("DFS遍历结果:")
DFS(visited, graph, 0)
```
BFS算法:
```python
from queue import Queue
def BFS(visited, graph, node):
q = Queue()
visited.add(node)
q.put(node)
while not q.empty():
node = q.get()
print(node, end=" ")
for neighbor in range(len(graph[node])):
if graph[node][neighbor] == 1 and neighbor not in visited:
visited.add(neighbor)
q.put(neighbor)
# 示例代码
graph = [[0, 1, 1, 0, 0],
[1, 0, 0, 1, 1],
[1, 0, 0, 1, 0],
[0, 1, 1, 0, 1],
[0, 1, 0, 1, 0]]
visited = set() # 用集合来存储已经访问过的节点
print("BFS遍历结果:")
BFS(visited, graph, 0)
```
阅读全文