šŸ”„ 0
⭐ 0
Lesson 9 of 10 15 min +100 XP

Graphs

A Graph is a non-linear data structure consisting of vertices (nodes) and edges (connections). Graphs can represent any relationship between objects.

Graph Data Structure

Graph Terminology

TermDefinition
Vertex (Node)A point in the graph
EdgeConnection between two vertices
DirectedEdges have direction (one-way)
UndirectedEdges are bidirectional
WeightedEdges have values (costs, distances)
PathSequence of vertices connected by edges
CyclePath that starts and ends at same vertex
DegreeNumber of edges connected to a vertex

Types of Graphs

Undirected          Directed            Weighted
  A---B             A→→→B               A--5--B
  |   |             ↑   ↓               |     |
  D---C             D←←←C               3     2
                                        |     |
                                        D--4--C

Graph Representation

1. Adjacency List (Most Common)

Each vertex stores a list of its neighbors.

const graph = {
  'A': ['B', 'D'],
  'B': ['A', 'C', 'E'],
  'C': ['B', 'F'],
  'D': ['A', 'E'],
  'E': ['B', 'D', 'F'],
  'F': ['C', 'E']
};
Space: O(V + E) — Efficient for sparse graphs

2. Adjacency Matrix

2D array where matrix[i][j] = 1 if edge exists.

//     A  B  C  D
// A [ 0, 1, 0, 1 ]
// B [ 1, 0, 1, 0 ]
// C [ 0, 1, 0, 1 ]
// D [ 1, 0, 1, 0 ]

const matrix = [
  [0, 1, 0, 1],
  [1, 0, 1, 0],
  [0, 1, 0, 1],
  [1, 0, 1, 0]
];
Space: O(V²) — Better for dense graphs

Graph Traversals

Breadth-First Search (BFS)

Explores level by level using a queue.

function bfs(graph, start) {
  const visited = new Set();
  const queue = [start];
  const result = [];

  visited.add(start);

  while (queue.length > 0) {
    const vertex = queue.shift();
    result.push(vertex);

    for (const neighbor of graph[vertex]) {
      if (!visited.has(neighbor)) {
        visited.add(neighbor);
        queue.push(neighbor);
      }
    }
  }

  return result;
}

// bfs(graph, 'A') → ['A', 'B', 'D', 'C', 'E', 'F']
Use cases: Shortest path (unweighted), level-order traversal

Depth-First Search (DFS)

Goes as deep as possible using a stack (or recursion).

function dfs(graph, start) {
  const visited = new Set();
  const result = [];

  function explore(vertex) {
    visited.add(vertex);
    result.push(vertex);

    for (const neighbor of graph[vertex]) {
      if (!visited.has(neighbor)) {
        explore(neighbor);
      }
    }
  }

  explore(start);
  return result;
}

// dfs(graph, 'A') → ['A', 'B', 'C', 'F', 'E', 'D']
Use cases: Cycle detection, topological sort, maze solving

BFS vs DFS

AspectBFSDFS
Data StructureQueueStack/Recursion
ApproachLevel by levelGo deep first
Shortest PathYes (unweighted)No
MemoryO(V) worstO(V) worst
Use CaseShortest pathCycle detection

Complexity

OperationAdjacency ListAdjacency Matrix
Add VertexO(1)O(V²)
Add EdgeO(1)O(1)
Remove EdgeO(E)O(1)
Query EdgeO(V)O(1)
BFS/DFSO(V + E)O(V²)
SpaceO(V + E)O(V²)

Common Graph Algorithms

AlgorithmPurpose
Dijkstra'sShortest path (weighted)
Bellman-FordShortest path (negative weights)
Kruskal's/Prim'sMinimum spanning tree
Topological SortOrder dependencies
Floyd-WarshallAll pairs shortest path

Real-World Applications

  • Social Networks — Friends, followers, connections
  • Maps & Navigation — Roads, shortest routes
  • Web Crawling — Pages linked to other pages
  • Recommendation Systems — Product relationships
  • Dependency Resolution — Package managers, build systems

What's Next?

Congratulations! You've completed the core data structures. The final lesson is a comprehensive quiz to test your understanding of everything you've learned.

🧠 Quick Quiz

Test your understanding of this lesson.

1

What are the two main components of a graph?

2

Which traversal explores all neighbors before going deeper?

3

What data structure does DFS typically use?

Trees