BFS and DFS in Data Structure: Concepts and Differences

If you’ve ever tried to navigate through a maze or looked for the shortest route in Google Maps, then knowingly or not you’ve experienced graph traversal. In the world of Data Structures and Algorithms (DSA), this concept shows up as BFS (Breadth First Search) and DFS (Depth First Search).

These two traversal techniques are core to mastering not just graphs, but also trees, networks, and even puzzles like Sudoku.

BFS and DFS in Data Structure

So let’s unpack everything: how BFS and DFS work, where they shine (and where they don’t), their differences, and how to implement them with real code examples in C. 

Want to master DSA with expert guidance? 


Explore Uncodemy’s DSA Course designed for beginners and advanced learners alike. 

What Is Graph Traversal Anyway? 

Think of a graph as a network of connected dots cities on a map, friends in a social network, or links on a webpage. 

Graph traversal simply means visiting each node (or vertex) in some defined order. That’s where BFS and DFS step in. 

What is BFS (Breadth-First Search)? 

BFS is like checking all neighbors before going deeper. 

Imagine you’re in a building looking for someone BFS is like visiting every room on the ground floor first before climbing the stairs to the next. 

 Characteristics: 

  • Traverses level by level 
  • Uses a queue data structure (FIFO) 
  • Great for finding the shortest path
  •  

BFS Real-Life Uses: 

  • GPS navigation (shortest path) 
  • Social network friend suggestions 
  • Crawling web pages 
  •  

  BFS Algorithm (Concept) 

1. Start from a selected node (source) 

2. Visit and mark it as visited 

3. Enqueue all adjacent unvisited nodes 

4. Dequeue the first element, repeat from step 2 

BFS Code in C 

Copy Code

#include <stdio.h> 

#include <stdlib.h> 

#define SIZE 100 

int queue[SIZE], front = -1, rear = -1; 

int visited[SIZE]; 

void enqueue(int value) { 

    if (rear == SIZE - 1) 

        return; 

    if (front == -1) 

        front = 0; 

    queue[++rear] = value; 

} 

int dequeue() { 

    if (front == -1 || front > rear) 

        return -1; 

    return queue[front++]; 

} 

void bfs(int graph[][SIZE], int vertices, int start) { 

    enqueue(start); 

    visited[start] = 1; 

    while (front <= rear) { 

        int current = dequeue(); 

        printf("%d ", current); 

        for (int i = 0; i < vertices; i++) { 

            if (graph[current][i] && !visited[i]) { 

                enqueue(i); 

                visited[i] = 1; 

            } 

        } 

    } 

}

 What is DFS (Depth-First Search)? 

DFS dives deep before backtracking. It's like following one hallway all the way to the end before checking the others. 

 Characteristics: 

  • Traverses deeply before backtracking 
  • Uses a stack (or recursion) 
  • Great for exploring all paths 
  •  

DFS Real-Life Uses: 

  • Puzzle solving (Sudoku, Maze) 
  • Detecting cycles in graphs 
  • Topological sorting 
  •  

DFS Algorithm (Concept) 

1. Start at the root 

2. Mark it as visited 

3. Visit an unvisited neighbor recursively 

4. Backtrack when needed 

DFS Code in C (Recursive) 

Copy Code

#include <stdio.h> 

int visited[100]; 

void dfs(int graph[][100], int vertex, int nodes) { 

    printf("%d ", vertex); 

    visited[vertex] = 1; 

    for (int i = 0; i < nodes; i++) { 

        if (graph[vertex][i] && !visited[i]) { 

            dfs(graph, i, nodes); 

        } 

    } 

}

 Key Differences Between BFS and DFS 

Feature BFS DFS 
Data Structure Used Queue Stack or Recursion 
Traversal Style Level-by-Level Depth-first 
Memory Usage High (stores all neighbors) Lower in many cases 
Optimal for Shortest Path Exploring complete paths 
Example Applications GPS, Social Networks Puzzles, Dependency Graphs 

 

When to Use BFS vs DFS? 

Scenario Use BFS or DFS? 
Finding shortest path BFS 
Solving mazes/puzzles DFS 
Detecting cycles in graphs DFS 
Web crawlers BFS 
Analyzing dependencies DFS 

Still confused when to pick which? Uncodemy's expert-led DSA course covers such decision-making with real projects and live sessions. 

 Common Mistakes to Avoid 

  • Not marking nodes as visited: Leads to infinite loops 
  • Incorrect queue/stack usage: Wrong traversal order 
  • Assuming graphs are trees: Not all graphs are hierarchical 
  • Skipping disconnected components: In BFS/DFS, always account for all nodes 

 Hybrid Approaches: When BFS Meets DFS 

Sometimes, problems require a mix. For example: 

  • Use BFS to find the shortest path. 
  • Then apply DFS to list all possible paths. 

Think of it like Google Maps showing the fastest route (BFS) and also giving you alternate routes (DFS-style depth search). 

 BFS vs DFS in Interview Questions 

You’ll often find questions like: 

  • “How would you detect a cycle in a directed graph?” 
    → DFS with visited + recursion stack. 
  • “How would you find the shortest path between two nodes?” 
    → BFS from the source node. 
  • “Write a function to traverse all components in a disconnected graph.” 
    → Use a loop to call BFS/DFS for unvisited nodes. 

So, understanding the depth vs breadth distinction isn’t just theory it’s a toolset you’ll use across coding rounds. 

 Learning Resources 

  • DSA Visualizer Tools like VisuAlgo or GraphOnline 
  • Uncodemy DSA Course 
  • Practice platforms: LeetCode, HackerRank, Codeforces 

 Frequently Asked Questions (FAQs) 

Q1. Which is faster: BFS or DFS? 

It depends. BFS is usually faster for shortest path problems, while DFS can be faster in deep graph traversal scenarios. 

Q2. Is DFS always recursive? 

Nope! DFS can also be implemented using a stack (iterative version), though recursion is more common. 

Q3. Do both BFS and DFS work on trees? 

Yes — in fact, tree traversals like level-order or in-order are specialized versions of BFS/DFS. 

Q4. Which one consumes more memory? 

Typically, BFS uses more memory due to queue usage and level-wise storage. 

Q5. Can BFS or DFS work on weighted graphs? 

They can traverse them, but for shortest paths in weighted graphs, use Dijkstra’s or A* algorithm instead. 

 Final Thoughts 

BFS and DFS are not just academic topics they’re practical problem-solving tools. Whether you’re building a game, working on AI pathfinding, or cracking coding interviews, knowing when and how to use them is a game changer. 

And let’s be real graph questions show up everywhere in tech interviews. The more hands-on practice you do, the more intuitive these algorithms become. 

Ready to master graph algorithms like BFS & DFS with mentorship, notes, and live doubt sessions? 
Check out Uncodemy’s Data Structures Course and start building your DSA foundation today. 

Bottom of Form 

Placed Students

Our Clients

Partners

...

Uncodemy Learning Platform

Uncodemy Free Premium Features

Popular Courses