python | 算法-图的深度优先遍历
数据结构
与上一篇同:python | 算法-图的宽度优先遍历
深度优先搜索
# 深度优先搜索(Depth First Search)
class DFS:
def dfs(self, start): # 从start开始做深度优先遍历
if start is None:
return
stack = [start]
set = [start]
print(start.value)
while len(stack) > 0:
cur = stack.pop()
for next in cur.nexts:
if next not in set:
stack.append(cur)
stack.append(next)
set.append(next)
print(next.value)
break
# test
m = [[1, 1, 2],
[1, 1, 3],
[1, 2, 5],
[1, 3, 2],
[1, 3, 4],
[1, 4, 5]]
generator = GraphGenerator()
g = generator.createGraph(m)
search = DFS()
print("从1开始深度优先搜索:")
search.dfs(g.nodes[1])
# 输出
# 从1开始深度优先搜索:
# 1
# 2
# 5
# 3
# 4
参考链接:https://github.com/algorithmzuo/algorithmbasic2020/blob/master/src/class16/Code02_DFS.java