Open In App

Difference between BFS and DFS

Last Updated : 29 May, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Breadth-First Search (BFS) and Depth-First Search (DFS) are two fundamental algorithms used for traversing or searching graphs and trees. This article covers the basic difference between Breadth-First Search and Depth-First Search.

bfs-vs-dfs-(1)

Difference between BFS and DFS

Breadth-First Search (BFS):

BFS, Breadth-First Search, is a vertex-based technique for finding the shortest path in the graph. It uses a Queue data structure that follows first in first out. In BFS, one vertex is selected at a time when it is visited and marked then its adjacent are visited and stored in the queue. It is slower than DFS. 
Example:

 Input:
A
/ \
B C
/ / \
D E F

Output: 

A, B, C, D, E, F

Code:

C++
#include <iostream>
#include <list>

using namespace std;

// This class represents a directed graph using adjacency
// list representation
class Graph {
    int V; // No. of vertices

    // Pointer to an array containing adjacency lists
    list<int>* adj;

public:
    Graph(int V); // Constructor

    // function to add an edge to graph
    void addEdge(int v, int w);

    // prints BFS traversal from a given source s
    void BFS(int s);
};

Graph::Graph(int V)
{
    this->V = V;
    adj = new list<int>[V];
}

void Graph::addEdge(int v, int w)
{
    adj[v].push_back(w); // Add w to v’s list.
}

void Graph::BFS(int s)
{
    // Mark all the vertices as not visited
    bool* visited = new bool[V];
    for (int i = 0; i < V; i++)
        visited[i] = false;

    // Create a queue for BFS
    list<int> queue;

    // Mark the current node as visited and enqueue it
    visited[s] = true;
    queue.push_back(s);

    // 'i' will be used to get all adjacent vertices of a
    // vertex
    list<int>::iterator i;

    // Create a mapping from integers to characters
    char map[6] = { 'A', 'B', 'C', 'D', 'E', 'F' };

    while (!queue.empty()) {
        // Dequeue a vertex from queue and print it
        s = queue.front();
        cout << map[s] << " "; // Use the mapping to print
                               // the original label
        queue.pop_front();

        // Get all adjacent vertices of the dequeued vertex
        // s If a adjacent has not been visited, then mark
        // it visited and enqueue it
        for (i = adj[s].begin(); i != adj[s].end(); ++i) {
            if (!visited[*i]) {
                queue.push_back(*i);
                visited[*i] = true;
            }
        }
    }
}

int main()
{
    // Create a graph given in the diagram
    /*     A
          / \
         B   C
        /   / \
       D   E   F
    */
    Graph g(6);
    g.addEdge(0, 1);
    g.addEdge(0, 2);
    g.addEdge(1, 3);
    g.addEdge(2, 4);
    g.addEdge(2, 5);

    cout << "Breadth First Traversal is: ";
    g.BFS(0); // Start BFS from A (0)

    return 0;
}
Python
from collections import deque

# This class represents a directed graph using adjacency list representation


class Graph:
    def __init__(self, V):
        self.V = V  # No. of vertices
        self.adj = [[] for _ in range(V)]  # Adjacency lists

    # Function to add an edge to graph
    def addEdge(self, v, w):
        self.adj[v].append(w)  # Add w to v’s list

    # Prints BFS traversal from a given source s
    def BFS(self, s):
        # Mark all the vertices as not visited
        visited = [False] * self.V

        # Create a queue for BFS
        queue = deque()

        # Mark the current node as visited and enqueue it
        visited[s] = True
        queue.append(s)

        # Create a mapping from integers to characters
        mapping = ['A', 'B', 'C', 'D', 'E', 'F']

        while queue:
            # Dequeue a vertex from queue and print it
            s = queue.popleft()
            # Use the mapping to print the original label
            print(mapping[s], end=" ")

            # Get all adjacent vertices of the dequeued vertex s
            # If an adjacent has not been visited, then mark it visited
            # and enqueue it
            for i in self.adj[s]:
                if not visited[i]:
                    queue.append(i)
                    visited[i] = True


if __name__ == "__main__":
    # Create a graph given in the diagram
    #      A
    #     / \
    #    B   C
    #   /   / \
    #  D   E   F
    g = Graph(6)
    g.addEdge(0, 1)
    g.addEdge(0, 2)
    g.addEdge(1, 3)
    g.addEdge(2, 4)
    g.addEdge(2, 5)

    print("Breadth First Traversal is: ", end="")
    g.BFS(0)  # Start BFS from A (0)
JavaScript
// This class represents a directed graph using adjacency list representation
class Graph {
    constructor(V) {
        this.V = V; // No. of vertices
        this.adj = new Array(V).fill(null).map(() => []); // Array of adjacency lists
    }

    // Function to add an edge to graph
    addEdge(v, w) {
        this.adj[v].push(w); // Add w to v’s list.
    }

    // Function to perform BFS traversal from a given source s
    BFS(s) {
        // Mark all the vertices as not visited
        let visited = new Array(this.V).fill(false);

        // Create a queue for BFS
        let queue = [];

        // Mark the current node as visited and enqueue it
        visited[s] = true;
        queue.push(s);

        // Mapping from integers to characters
        let map = ['A', 'B', 'C', 'D', 'E', 'F'];

        while (queue.length > 0) {
            // Dequeue a vertex from queue and print it
            s = queue.shift();
            console.log(map[s] + " "); // Use the mapping to print the original label

            // Get all adjacent vertices of the dequeued vertex s
            // If an adjacent has not been visited, then mark it visited
            // and enqueue it
            for (let i of this.adj[s]) {
                if (!visited[i]) {
                    queue.push(i);
                    visited[i] = true;
                }
            }
        }
    }
}

// Main function
function main() {
    // Create a graph given in the diagram
    /*     A
          / \
         B   C
        /   / \
       D   E   F
    */
    let g = new Graph(6);
    g.addEdge(0, 1);
    g.addEdge(0, 2);
    g.addEdge(1, 3);
    g.addEdge(2, 4);
    g.addEdge(2, 5);

    console.log("Breadth First Traversal is: ");
    g.BFS(0); // Start BFS from A (0)
}

// Run the main function
main();

Output
Breadth First Traversal is: A B C D E F 

Depth First Search (DFS):

DFS, Depth First Search, is an edge-based technique. It uses the Stack data structure and performs two stages, first visited vertices are pushed into the stack, and second if there are no vertices then visited vertices are popped. 
Example: 

  Input:
A
/ \
B D
/ / \
C E F

Output: 

A, B, C, D, E, F

Difference Between BFS and DFS:

ParametersBFSDFS
Stands forBFS stands for Breadth First Search.DFS stands for Depth First Search.
Data StructureBFS(Breadth First Search) uses Queue data structure for finding the shortest path.DFS(Depth First Search) uses Stack data structure.
DefinitionBFS is a traversal approach in which we first walk through all nodes on the same level before moving on to the next level.  DFS is also a traversal approach in which the traverse begins at the root node and proceeds through the nodes as far as possible until we reach the node with no unvisited nearby nodes.
Conceptual DifferenceBFS builds the tree level by level.DFS builds the tree sub-tree by sub-tree.
Approach usedIt works on the concept of FIFO (First In First Out). It works on the concept of LIFO (Last In First Out).
Suitable forBFS is more suitable for searching vertices closer to the given source.DFS is more suitable when there are solutions away from source.
ApplicationsBFS is used in various applications such as bipartite graphs, shortest paths, etc.DFS is used in various applications such as acyclic graphs and finding strongly connected components etc.

Please also see BFS vs DFS for Binary Tree for the differences for a Binary Tree Traversal. 



Previous Article
Next Article

Similar Reads

Illustrate the difference in peak memory consumption between DFS and BFS
To understand this let's take a binary tree If we conduct BFS in this tree: In level 0 there is one node in the memory In level 1 there are two nodes in the memory In level 2 there are four nodes in the memory In level 3 there are eight nodes in the memory But in the case of DFS in this tree, you'll never have more than 4 nodes in memory The differ
1 min read
Time and Space Complexity of DFS and BFS Algorithm
The time complexity of both Depth-First Search (DFS) and Breadth-First Search (BFS) algorithms is O(V + E), where V is the number of vertices and E is the number of edges in the graph. The space complexity of DFS is O(V), where V represents the number of vertices in the graph, and for BFS, it is O(V), where V represents the number of vertices in th
2 min read
Why is the complexity of both BFS and DFS O(V+E)?
The complexity of both BFS and DFS are O(V+E) because every vertex (V) and every edge (E) is explored only once. In graph theory, two fundamental algorithms used for traversing or searching tree or graph data structures are Breadth-First Search (BFS) and Depth-First Search (DFS). Let's look at Why is the complexity of both BFS and DFS is O(V+E). Wh
2 min read
When to use DFS or BFS to solve a Graph problem?
Generally, when we come across a graph problem, we might need to traverse the structure of the given graph or tree to find our solution to the problem. Our problem might be : To search for a particular node in the graph.To find the shortest distance from a node to any other node or to every other node.To count all the nodes.Or there can be more com
7 min read
BFS vs DFS for Binary Tree
Breadth-First Search (BFS) and Depth-First Search (DFS) for Binary Trees are ways to traverse nodes of the Binary Tree. This article aims to provide the basic difference between BFS and DFS for Binary Tree. A Tree is typically traversed in two ways:Breadth First Traversal (Or Level Order Traversal)Depth First TraversalsInorder Traversal (Left-Root-
3 min read
Difference between BFS and Dijkstra's algorithms when looking for shortest path?
What is Dijkstra's Algorithm? Dijkstra's Algorithm is used for finding the shortest path between any two vertices of a graph. It uses a priority queue for finding the shortest path. For more detail about Dijkstra's Algorithm, you can refer to this article. What is BFS Algorithm? Breadth First Search (BFS) algorithm traverses a graph in a bread towa
2 min read
Difference between Local File System (LFS) and Distributed File System (DFS)
1. Local File System (LFS) : The basic file system of Linux operating system is termed as Local file system. It stores any data file as it is in single copy. It stores data files in Tree format. Here, any user can access data files directly. LFS does not Replicate the data blocks. It always used for storing and processing personal data(small data).
3 min read
Minimum number of edges between two vertices of a graph using DFS
Given an undirected graph G(V, E) with N vertices and M edges. We need to find the minimum number of edges between a given pair of vertices (u, v). We have already discussed this problem using the BFS approach, here we will use the DFS approach. Examples: Input: For the following given graph, find the minimum number of edges between vertex pair (0,
10 min read
Print the path between any two nodes of a tree | DFS
Given a tree of distinct nodes N with N-1 edges and a pair of nodes P. The task is to find and print the path between the two given nodes of the tree using DFS. Input: N = 10 1 / \ 2 3 / | \ / | \ 4 5 6 7 8 9 Pair = {4, 8} Output: 4 -&gt; 2 -&gt; 1 -&gt; 3 -&gt; 8 Input: N = 3 1 / \ 2 3 Pair = {2, 3} Output: 2 -&gt; 1 -&gt; 3 For example, in the ab
15+ min read
Calculate number of nodes between two vertices in an acyclic Graph by DFS method
Given a connected acyclic graph consisting of V vertices and E edges, a source vertex src, and a destination vertex dest, the task is to count the number of vertices between the given source and destination vertex in the graph. Examples: Input: V = 8, E = 7, src = 7, dest = 8, edges[][] ={{1 4}, {4, 5}, {4, 2}, {2, 6}, {6, 3}, {2, 7}, {3, 8}}Output
10 min read
Article Tags :
Practice Tags :