深度优先搜索遍历
# 深度搜索算法遍历
def dfs(graph, start, step):
global path
global visited
path.append(start)
visited[start] = 0
for ner in graph[start]:
if visited[ner]==1:
dfs(graph, ner, step + 1)
# 图的遍历
# 构造邻接表
graph = {0: [2, 3], 1: [4, 5], 2: [0, 4], 3: [0, 5], 4: [1, 2, 6], 5: [1, 3, 6], 6: [4, 5]}
visited = {}
# n = int(input())
# for i in range(n):
# li = list(map(int, input().split())) # 根据输入格式变换
# graph[i] = li[1:]
for j in graph:
visited[j] = 1 # 没有被访问的点值为1
path = []
dfs(graph, 0, 1)
print(graph)
print(visited)
print(path)
运行结果
求最长路径
# 求最长路径
def dfs(graph, start, step):
global path
global visited
global maxle
global end
global temp
temp.append(start)
visited[start] = 0
if maxle < step and start == end:
maxle = step
path = temp
for ner in graph[start]:
if visited[ner]==1:
dfs(graph, ner, step + 1)
temp = temp[:-1]
# 图
graph = {0: [2, 3], 1: [4, 5], 2: [0, 4], 3: [0, 5], 4: [1, 2, 6], 5: [1, 3, 6], 6: [4, 5]}
n = 6 # 结点总数
start = 0
end = 6
visited = {}
path = []
maxle = 0
temp = []
for j in graph:
visited[j] = 1
dfs(graph, start, 1)
print(path)
结果