赞
踩
深度优先遍历(Depth First Search, 简称 DFS) 与广度优先遍历(Breath First Search)是图论中两种非常重要的算法,生产上广泛用于拓扑排序,寻路(走迷宫),搜索引擎,爬虫等,也频繁出现在 leetcode,高频面试题中。
主要思路是从图中一个未访问的顶点 V 开始,沿着一条路一直走到底,然后从这条路尽头的节点回退到上一个节点,再从另一条路开始走到底…,不断递归重复此过程,直到所有的顶点都遍历完成,它的特点是不撞南墙不回头,先走完一条路,再换一条路继续走。
树是图的一种特例(连通无环的图就是树),接下来我们来看看树用深度优先遍历该怎么遍历。
# 深度遍历目录
import os,collections
path = r'D:\test\work_file\meishi'
def GetAllDirDeep(path):
stack = []
stack.append(path)
# 处理栈,当栈为空时结束循环
while len(stack) != 0:
# 从栈里取出数据
DirPath = stack.pop()
#print("DirPath =",DirPath)
# 目录下所有文件
FileList = os.listdir(DirPath)
#print("FileList =",FileList)
# 循环处理每个文件
for FileName in FileList:
FileAbsPath = os.path.join(DirPath,FileName)
#print("FileName ",FileName)
if os.path.isfile(FileAbsPath) == True:
print("是文件",FileAbsPath)
else:
print("是目录",FileAbsPath)
stack.append(FileAbsPath)
GetAllDirDeep(path)
广度优先遍历,指的是从图的一个未遍历的节点出发,先遍历这个节点的相邻节点,再依次遍历每个相邻节点的相邻节点。
上文所述树的广度优先遍历动图如下,每个节点的值即为它们的遍历顺序。所以广度优先遍历也叫层序遍历,先遍历第一层(节点 1),再遍历第二层(节点 2,3,4),第三层(5,6,7,8),第四层(9,10)。
深度优先遍历用的是栈,而广度优先遍历要用队列来实现,我们以下图二叉树为例来看看如何用队列来实现广度优先遍历。
import os,collections
path = r'D:\test\work_file\meishi'
# 广度遍历目录
def GetAllDirScope(path):
queue = collections.deque()
# 进队
queue.append(path)
print("queue =",queue)
while len(queue) != 0:
# 出队数据
FilePath = queue.popleft()
#print(FilePath)
# 找出所有的文件
FileNameList = os.listdir(FilePath)
for FileName in FileNameList:
#print(FileName)
FileAbsPath = os.path.join(FilePath,FileName)
if os.path.isfile(FileAbsPath) == True:
print("是文件",FileAbsPath)
else:
print("是目录",FileAbsPath)
queue.append(FileAbsPath)
GetAllDirScope(path)
import os,collections
path = r'D:\test\work_file\meishi'
def GetAllDir(path):
FileList = os.listdir(path)
for FileName in FileList:
NewFileName = path + "\\" + FileName
print("NewFileName =",NewFileName)
if os.path.isdir(NewFileName):
print("是目录")
GetAllDir(NewFileName)
else:
print("是文件")
GetAllDir(path)
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。