Back to DSA DashboardConcept Mastery
DSA Core Concept

Graphs

A Graph is a non-linear data structure containing vertices (nodes) connected by edges. They can be directed or undirected, weighted or unweighted, and represented as adjacency matrices or lists.

Why It Exists

Many real-world networks (roads, social connections, computer grids) cannot be represented hierarchically. Graphs model cyclic, multi-path relationships.

Intuition for Beginners

Think of a flight route map. Cities are vertices. Flight paths are edges. To find a connection from New York to Paris, you trace paths across cities, checking for layovers and ticket costs.

Visual Explanation

Undirected Graph Network:
   (A) ------- (B)
    |         / |
    |       /   |
    |     /     |
   (C) ------- (D)
Interactive Visualizer

BFS Grid Search

1 / 3
Enqueue start cell

Add coordinate (0,0) to queue. Mark as visited.

State KeyValue
grid[["S",0],[0,"E"]]
queue[[0,0]]
visited["0,0"]
💡 Use the arrows above to trace states dynamically.

Complexity Analysis

Search AlgorithmTime ComplexitySpace ComplexityNotes
BFS (Queue)O(V + E)O(V)Shortest path on unweighted graphs
DFS (Stack)O(V + E)O(V)Path connectivity and cycle checks
DijkstraO((V+E) log V)O(V)Shortest path on weighted graphs

Production & Real World Applications

  • GPS Navigation: Finding the fastest driving route across map intersections.
  • Social Networks: Suggesting friends based on mutual connection chains.

Algorithmic Patterns

Adjacency List Mapping

Mapping vertex keys to arrays of neighbor nodes to save memory compared to sparse matrices.

Topological Sort

Ordering DAG nodes linearly such that for edge U -> V, U appears before V (essential for package dependencies).

Defending the Design (Interview Q&A)

Q:When should we prefer BFS over DFS for graph traversal?
BFS is preferred when searching for the shortest path in unweighted graphs, as it explores nodes level-by-level (radiating outward). DFS is better for exploring complete paths (backtracking), topological sorts, or checking cycle connectivity.

Common Traps & Mistakes

  • ⚠️Infinite recursion loops due to missing 'visited' tracking arrays.
  • ⚠️Using Dijkstra on graphs containing negative edge weights (fails to relax correctly).

Practice Problems Mapping

Number of IslandsSolve
Clone GraphSolve

Related Concepts