Python implements depth-first traversal (DFS) and breadth-first traversal (BFS)

1. Introduction

Depth First Search (DFS) and Breadth First Search (Breath First Search) are two very important algorithms in graph theory. They are widely used in production for topological sorting, path finding (maze), search engines, and crawlers. And so on, also frequently appear in leetcode, high-frequency interview questions.

Second, depth-first traversal

The main idea is to start from an unvisited vertex V in the graph, go to the end along one road, then back to the previous node from the end of this road, and then go to the end from another road... Repeating recursively This process, until all the vertices are traversed, it is characterized by not hitting the south wall and not turning back, first finish one path, and then change another path to continue walking.

A tree is a special case of a graph (a connected acyclic graph is a tree). Next, let's take a look at how to traverse the tree using depth-first traversal.

Insert picture description here

  1. We start traversing from the root node 1, and its adjacent nodes are 2, 3, 4. First traverse node 2, then traverse the child node 5 of 2, and then traverse the child node 9 of 5.
    Insert picture description here
  2. In the above figure, a road has been reached to the end (9 is a leaf node, and there are no more traversable nodes). At this time, go back to the previous node 5 from 9 to see if there are any nodes other than 9 in node 5, there is no Continue to fall back to 2, and 2 has no nodes other than 5, and fall back to 1, and 1 has node 3 other than 2, so the depth-first traversal starts from node 3, as follows:Insert picture description here
  3. In the same way, starting from 10 and going back up to 6, 6 has no child nodes other than 10, and then going back up, it is found that 3 has child 7 other than 6, so it will traverse 7 at this time.
    Insert picture description here
  4. Go back from 7 to 3 and 1, and find that 1 and node 4 have not been traversed, so at this time, traverse along 4 and 8, so that the traversal is completed.
    The traversal sequence of the complete node is as follows (the blue number on the node represents):
    Insert picture description here
# 深度遍历目录
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)

Third, breadth-first traversal

Breadth-first traversal refers to starting from an untraversed node in the graph, first traversing the adjacent nodes of this node, and then traversing the adjacent nodes of each adjacent node in turn.

The breadth-first traversal graph of the tree described above is as follows, the value of each node is their traversal order. So breadth-first traversal is also called layer sequence traversal, first traverse the first layer (node ​​1), then traverse the second layer (nodes 2, 3, 4), the third layer (5, 6, 7, 8), the fourth layer (9, 10).

Insert picture description here
Depth-first traversal uses a stack, while breadth-first traversal is implemented with queues. Let's take a binary tree as an example to see how to use queues to implement breadth-first traversal.
Insert picture description here

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)

Four, traverse using recursion

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)

Guess you like

Origin blog.csdn.net/zhuan_long/article/details/109999242