Algorithms 101: DFS and BFS

Depth-First Search (DFS) and Breadth-First Search (BFS) are two common traversal methods for trees and graphs


Tree Traversal

Depth-First Search (DFS) is an algorithm that traverses the nodes of a tree by searching the branches as deeply as possible. It traverses the nodes of the tree along its depth, exploring the branches as deeply as possible.

  • In the depth-first traversal of a tree, we first visit the root node and then recursively perform a depth-first traversal on each subtree rooted at the root node.
class TreeNode:
    def __init__(self, value):
        self.value = value
        self.children = []

    def add_child(self, child_node):
        self.children.append(child_node)

    def dfs_traversal(self):
        print(self.value)
        for child in self.children:
            child.dfs_traversal()

root = TreeNode('A') # 创建一个简单的树结构
child1 = TreeNode('B')
child2 = TreeNode('C')
child3 = TreeNode('D')
root.add_child(child1)
root.add_child(child2)
child1.add_child(child3)

root.dfs_traversal() # 进行深度优先遍历

Tree dfs_traversal

def dfs_traversal(self):
        print(self.value)
        for child in self.children:
            child.dfs_traversal()

Breadth-First Search (BFS) is an algorithm that traverses the tree by visiting the nodes layer by layer. It starts from the root node, visits all nodes adjacent to the root node, and then traverses down layer by layer.

  • In the breadth-first traversal, we first visit the root node and then sequentially visit each node at each level.
from collections import deque

class TreeNode:
    def __init__(self, value):
        self.value = value
        self.children = []

    def add_child(self, child_node):
        self.children.append(child_node)

    def bfs_traversal(self):
        queue = deque([self])  # 使用双端队列来实现 BFS
        while queue:
            node = queue.popleft()  # 从队列左侧取出节点
            print(node.value)
            queue.extend(node.children)  # 将节点的子节点加入队列

root = TreeNode('A') # 创建一个简单的树结构
child1 = TreeNode('B')
child2 = TreeNode('C')
child3 = TreeNode('D')
root.add_child(child1)
root.add_child(child2)
child1.add_child(child3)

root.bfs_traversal() # 进行广度优先遍历

Tree bfs_traversal

 def bfs_traversal(self):
        queue = deque([self])  # 使用双端队列来实现 BFS
        while queue:
            node = queue.popleft()  # 从队列左侧取出节点
            print(node.value)
            queue.extend(node.children)  # 将节点的子节点加入队列

For example, breadth-first search is usually more suitable for finding the shortest path or traversing the entire tree. In some cases, depth-first search may be more appropriate.These two traversal methods have different applications in different scenarios. For example, breadth-first search is usually more suitable for finding the shortest path or traversing the entire tree. In some cases, depth-first search may be more appropriate.


Graph Traversal

Comments

2 responses to “Algorithms 101: DFS and BFS”

  1. admin Avatar

    Depth-First Search and Breadth-First Search
    Depth-First Search (DFS) and Breadth-First Search (BFS) are two common graph traversal algorithms, each with its own characteristics and applications.
    Depth-First Search (DFS):
    DFS is an algorithm that traverses a graph or tree by exploring as far as possible along each branch before backtracking.
    It starts from the top node and follows a path to reach the end node of the path
    .
    The time complexity of DFS is O(V + E), where V is the number of vertices and E is the number of edges in the graph
    .
    DFS is often used for tasks such as topological sorting, finding connected components, and solving puzzles with only one solution.
    Breadth-First Search (BFS):
    BFS is an algorithm that systematically traverses the graph by exploring each level or layer before moving on to the next.
    It starts from the top node in the graph and travels down until it reaches the root node
    .
    The time complexity of BFS is also O(V + E), where V is the number of vertices and E is the number of edges in the graph
    .
    BFS is commonly used for finding the shortest path, solving puzzles with multiple solutions, and network broadcasting.
    Both algorithms have their own advantages and are suitable for different scenarios. While BFS is often used for finding the shortest path or traversing the entire graph, DFS is more commonly used due to its practicality and space complexity

  2. admin Avatar

    深度与广度优先遍历
    深度优先遍历(DFS)和广度优先遍历(BFS)是树和图的两种常见遍历方式。
    深度优先遍历(DFS)是一种通过尽可能深地搜索树的分支来遍历树的节点的算法。它沿着树的深度遍历树的节点,尽可能深地搜索树的分支。
    广度优先遍历(BFS)是一种通过逐层访问树的节点来遍历树的算法。它从根节点开始,首先访问所有与根节点相邻的节点,然后再逐层向下遍历。
    在树的深度优先遍历中,我们首先访问根节点,然后递归地对根节点的每个子树进行深度优先遍历。而在广度优先遍历中,我们首先访问根节点,然后按照层级顺序依次访问每一层的节点。
    这两种遍历方式在不同的情况下有不同的应用,比如在寻找最短路径或者遍历整个树的情况下,广度优先遍历通常更为适用。而在某些情况下,深度优先遍历可能更为合适

Leave a Reply

Your email address will not be published. Required fields are marked *