深度优先搜索的Python语言模板
时间: 2023-11-05 21:02:56 浏览: 82
# 定义深度优先搜索函数
def dfs(node, visited):
# 如果当前节点已经被访问过,则返回
if visited[node]:
return
# 标记当前节点为已访问
visited[node] = True
# 处理当前节点
# ...
# 递归遍历当前节点的邻居节点
for neighbor in node.neighbors:
dfs(neighbor, visited)
# 创建图的节点类
class Node:
def __init__(self, val):
self.val = val
self.neighbors = []
# 创建图的节点
node1 = Node(1)
node2 = Node(2)
node3 = Node(3)
# 构建图的邻接表
node1.neighbors = [node2, node3]
node2.neighbors = [node1]
node3.neighbors = [node1]
# 初始化节点访问状态
visited = [False] * 3
# 从节点1开始进行深度优先搜索
dfs(node1, visited)
阅读全文