The Wayback Machine - https://web.archive.org/web/20240827002005/https://www.geeksforgeeks.org/difference-between-bfs-and-dfs/
Open In App

Difference between BFS and DFS

Last Updated : 29 May, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow
Companies:
Show Topics
Solve Problem
Easy
63.07%
2.7L

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)
In computers, file systems are essential components that help in managing how data will be stored and retrieved. It provides a structural way to store, organize and manage data on various storage devices such as USBs, hard drives, SSDs, etc. Different file systems have been created to meet the increasing demand for data processing and storage. The
4 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
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
Applications, Advantages and Disadvantages of Breadth First Search (BFS)
We have earlier discussed Breadth First Traversal Algorithm for Graphs. Here in this article, we will see the applications, advantages, and disadvantages of the Breadth First Search. Applications of Breadth First Search: 1. Shortest Path and Minimum Spanning Tree for unweighted graph: In an unweighted graph, the shortest path is the path with the l
4 min read
Time and Space Complexity of Breadth First Search (BFS)
What is Breadth First Search?The Breadth First Search (BFS) algorithm is used to search a graph data structure for a node that meets a set of criteria. It starts at the root of the graph and visits all nodes at the current depth level before moving on to the nodes at the next depth level. Although there are other methods for traversing the graph, B
3 min read
Tree, Back, Edge and Cross Edges in DFS of Graph
Consider a directed graph given in below, DFS of the below graph is 1 2 4 6 3 5 7 8. In below diagram if DFS is applied on this graph a tree is obtained which is connected using green edges. Tree Edge: It is an edge which is present in the tree obtained after applying DFS on the graph. All the Green edges are tree edges. Forward Edge: It is an edge
11 min read
Printing pre and post visited times in DFS of a graph
Depth First Search (DFS) marks all the vertices of a graph as visited. So for making DFS useful, some additional information can also be stored. For instance, the order in which the vertices are visited while running DFS. Pre-visit and Post-visit numbers are the extra information that can be stored while running a DFS on a graph and which turns out
8 min read
Construct the Rooted tree by using start and finish time of its DFS traversal
Given start and finish times of DFS traversal of N vertices that are available in a Rooted tree, the task is to construct the tree (Print the Parent of each node). Parent of the root node is 0.Examples: Input: Start[] = {2, 4, 1, 0, 3}, End[] = {3, 5, 4, 5, 4} Output: 3 4 4 0 3 Given Tree is -: 4(0, 5) / \ (1, 4)3 2(4, 5) / \ (2, 3)1 5(3, 4) The ro
8 min read
Graph implementation using STL for competitive programming | Set 1 (DFS of Unweighted and Undirected)
We have introduced Graph basics in Graph and its representations. In this post, a different STL-based representation is used that can be helpful to quickly implement graphs using vectors. The implementation is for the adjacency list representation of the graph. Following is an example undirected and unweighted graph with 5 vertices. Below is an adj
7 min read
Time and Space Complexity of Depth First Search (DFS)
The time complexity of Depth First Search (DFS) is O(V + E), where V is the number of vertices and E is the number of edges. The space complexity is O(V) for a recursive implementation. Below are the detailed explanation of Time and Space Complexity of Depth First Search (DFS): Time Complexity of Depth First Search (DFS):Best Case of Depth First Se
2 min read
Applications, Advantages and Disadvantages of Depth First Search (DFS)
Depth First Search is a widely used algorithm for traversing a graph. Here we have discussed some applications, advantages, and disadvantages of the algorithm. Applications of Depth First Search:1. Detecting cycle in a graph: A graph has a cycle if and only if we see a back edge during DFS. So we can run DFS for the graph and check for back edges.
4 min read
Water Jug problem using BFS
You are given an m liter jug and a n liter jug. Both the jugs are initially empty. The jugs don’t have markings to allow measuring smaller quantities. You have to use the jugs to measure d liters of water where d is less than n. (X, Y) corresponds to a state where X refers to the amount of water in Jug1 and Y refers to the amount of water in Jug2 D
15+ min read
Diameter of n-ary tree using BFS
N-ary tree refers to the rooted tree in which each node having atmost k child nodes. The diameter of n-ary tree is the longest path between two leaf nodes. Various approaches have already been discussed to compute diameter of tree. Diameter of an N-ary tree Diameter of a Binary Tree in O(n) Diameter of a Binary Tree Diameter of a tree using DFS Thi
7 min read
Count the number of nodes at given level in a tree using BFS.
Given a tree represented as an undirected graph. Count the number of nodes at a given level l. It may be assumed that vertex 0 is the root of the tree. Examples: Input : 7 0 1 0 2 1 3 1 4 1 5 2 6 2 Output : 4 Input : 6 0 1 0 2 1 3 2 4 2 5 2 Output : 3 BFS is a traversing algorithm that starts traversing from a selected node (source or starting node
9 min read
BFS using vectors &amp; queue as per the algorithm of CLRS
Breadth-first search traversal of a graph using the algorithm given in CLRS book. BFS is one of the ways to traverse a graph. It is named so because it expands the frontier between discovered and undiscovered vertices uniformly across the breadth of the frontier. What it means is that the algorithm first discovers all the vertices connected to "u"
11 min read
Print the lexicographically smallest BFS of the graph starting from 1
Given a connected graph with N vertices and M edges. The task is to print the lexicographically smallest BFS traversal of the graph starting from 1. Note: The vertices are numbered from 1 to N.Examples: Input: N = 5, M = 5 Edges: 1 4 3 4 5 4 3 2 1 5 Output: 1 4 3 2 5 Start from 1, go to 4, then to 3 and then to 2 and to 5. Input: N = 3, M = 2 Edges
7 min read
Coin Change | BFS Approach
Given an integer X and an array arr[] of length N consisting of positive integers, the task is to pick minimum number of integers from the array such that they sum up to N. Any number can be chosen infinite number of times. If no answer exists then print -1.Examples: Input: X = 7, arr[] = {3, 5, 4} Output: 2 The minimum number elements will be 2 as
6 min read
Implementation of BFS using adjacency matrix
Breadth First Search (BFS) has been discussed in this article which uses adjacency list for the graph representation. In this article, adjacency matrix will be used to represent the graph. Adjacency matrix representation: In adjacency matrix representation of a graph, the matrix mat[][] of size n*n (where n is the number of vertices) will represent
7 min read
Word Ladder - Set 2 ( Bi-directional BFS )
Given a dictionary, and two words start and target (both of the same length). Find length of the smallest chain from start to target if it exists, such that adjacent words in the chain only differ by one character and each word in the chain is a valid word i.e., it exists in the dictionary. It may be assumed that the target word exists in the dicti
15+ min read
Find integral points with minimum distance from given set of integers using BFS
Given an integer array A[] of length N and an integer K. The task is to find K distinct integral points that are not present in the given array such that the sum of their distances from the nearest point in A[] is minimized. An integral point is defined as the point with both the coordinates as integers. Also, in the x-axis, we don't need to consid
9 min read
Check if the given permutation is a valid BFS of a given Tree
Given a tree with N nodes numbered from 1 to N and a permutation array of numbers from 1 to N. Check if it is possible to obtain the given permutation array by applying BFS (Breadth First Traversal) on the given tree.Note: Traversal will always start from 1.Example: Input: arr[] = { 1 5 2 3 4 6 } Edges of the given tree: 1 - 2 1 - 5 2 - 3 2 - 4 5 -
10 min read
Traversal of a Graph in lexicographical order using BFS
C/C++ Code // C++ program to implement // the above approach #include &lt;bits/stdc++.h&gt; using namespace std; // Function to traverse the graph in // lexicographical order using BFS void LexiBFS(map&lt;char, set&lt;char&gt; &gt;&amp; G, char S, map&lt;char, bool&gt;&amp; vis) { // Stores nodes of the graph // at each level queue&lt;char&gt; q; /
9 min read
Distance of each node of a Binary Tree from the root node using BFS
Given a Binary tree consisting of N nodes with values in the range [1, N], the task is to find the distance from the root node to every node of the tree. Examples: Input: 1 / \ 2 3 / \ \ 4 5 6 Output: 0 1 1 2 2 2 Explanation: The distance from the root to node 1 is 0. The distance from the root to node 2 is 1. The distance from the root to node 3 i
9 min read
Breadth First Traversal ( BFS ) on a 2D array
Given a matrix of size M x N consisting of integers, the task is to print the matrix elements using Breadth-First Search traversal. Examples: Input: grid[][] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}}Output: 1 2 5 3 6 9 4 7 10 13 8 11 14 12 15 16 Input: grid[][] = {{-1, 0, 0, 1}, {-1, -1, -2, -1}, {-1, -1, -1, -1}, {0, 0, 0,
9 min read
Article Tags :
Practice Tags :