#1 India's Top IT Training Institute
×

About Uncodemy

Know more about who we are and what we stand for.

About Us

About Us

Discover our mission to equip individuals with essential IT skills and industry expertise.

Read More →
UnCodeMy Gallery

UnCodeMy Gallery

Explore highlights from our IT training sessions and success stories.

Read More →
Mentors

Mentors

Meet the industry experts who train and guide you through your course.

Read More →
Free Resources

Free Resources

Free tutorials, interview questions, tools and calculators to help you learn.

Explore →
×

Free Resources

Learn, practice and plan your career — bilkul free.

Tutorials

Tutorials

Step-by-step written tutorials to learn any technology at your own pace.

Read More →
Free Counselling

Free Counselling

Book a free video counselling session and pick the right course for you.

Read More →
Online Compiler

Online Compiler

Write, run and test your code online — no setup required.

Read More →
Graph Algorithms

Breadth First Search vs Depth First Search

Breadth First Search (BFS) and Depth First Search (DFS) are the two fundamental algorithms for traversing or searching tree and graph data structures. They differ in the order they visit nodes and the data structures they rely on internally.

Breadth First Search (BFS)

BFS explores all neighbors of a node before moving to the next level, using a queue to track nodes to visit. It finds the shortest path in terms of number of edges in unweighted graphs.

from collections import deque

def bfs(graph, start):
    visited = {start}
    queue = deque([start])
    order = []
    while queue:
        node = queue.popleft()
        order.append(node)
        for neighbor in graph[node]:
            if neighbor not in visited:
                visited.add(neighbor)
                queue.append(neighbor)
    return order

Depth First Search (DFS)

DFS explores as far as possible along a branch before backtracking, using a stack (explicit or via recursion).

def dfs(graph, start, visited=None):
    if visited is None:
        visited = set()
    visited.add(start)
    order = [start]
    for neighbor in graph[start]:
        if neighbor not in visited:
            order.extend(dfs(graph, neighbor, visited))
    return order

Comparison Table

AspectBFSDFS
Data structureQueueStack / recursion
Memory usageHigher (stores whole frontier)Lower for deep/narrow graphs
Shortest path (unweighted)GuaranteedNot guaranteed
Use caseShortest path, level-order traversalTopological sort, cycle detection, connected components

Complexity

MetricBFSDFS
TimeO(V + E)O(V + E)
SpaceO(V)O(V)