Difference Between Bfs and Dfs

 Difference Between Bfs and Dfs 




BFS (Breadth-First Search) and DFS (Depth-First Search) are two commonly used graph traversal algorithms. They are used to explore and traverse the vertices and edges of a graph or tree data structure.


Here's the basic difference between BFS and DFS:


1.BFS (Breadth-First Search):

  • BFS starts from the root (or any arbitrary node) and explores all the neighboring nodes at the current depth level before moving on to the next level.
  • It uses a queue data structure to keep track of the nodes to visit.
  • BFS is useful when you need to find the shortest path from the source node to a destination node in an unweighted graph or when you want to explore all nodes at the same level before moving on to the next level.
  • Here's an example of BFS traversal in Python:
from collections import deque

def bfs(graph, start):
    visited = set()  # to keep track of visited nodes
    queue = deque([start])  # use deque as a queue, initially containing the starting node

    while queue:
        node = queue.popleft()  # dequeue the node from the front of the queue
        print(node)  # process the node (e.g., print it)

        if node not in visited:
            visited.add(node)  # mark the node as visited

        for neighbor in graph[node]:
            if neighbor not in visited:
                queue.append(neighbor)  # enqueue unvisited neighbors


2. DFS (Depth-First Search):
  • DFS starts from the root (or any arbitrary node) and explores as far as possible along each branch before backtracking.
  • It uses a stack data structure (or recursion) to keep track of the nodes to visit.
  • DFS is useful when you want to explore a graph or tree deeply, and may not necessarily find the shortest path or visit nodes at the same level together.
Here's an example of DFS traversal using recursion in Python:

def dfs(graph, node, visited):
    if node not in visited:
        visited.add(node)  # mark the node as visited
        print(node)  # process the node (e.g., print it)

        for neighbor in graph[node]:
            dfs(graph, neighbor, visited)  # recursively call DFS on unvisited neighbors


Note: In both BFS and DFS, the graph is typically represented as an adjacency list or an adjacency matrix, and the traversal can be customized based on the specific requirements of the problem.

Post a Comment

0 Comments