Graph

Vertices, edges, types, representation, BFS, DFS, and key graph algorithms

Introduction to Graphs

A Graph is a non-linear data structure consisting of Vertices (Nodes) and Edges (Connections). Graphs model relationships between objects and are one of the most widely used structures in computer science.

Graphs appear everywhere in real-world applications:

  • Social Networks (users as vertices, friendships as edges)
  • Google Maps and GPS navigation (cities as vertices, roads as edges)
  • Computer Networks (routers as vertices, links as edges)
  • Flight routes, recommendation systems, and web page links

Formally, a graph G is defined as:

G = (V, E)

V = Set of Vertices = {A, B, C, D}
E = Set of Edges    = {(A,B), (A,C), (B,D), (C,D)}

This gives a graph that looks like:

    A
   / \
  B   C
   \ /
    D

Basic Terminology

Understanding these terms is essential before diving into graph algorithms.

Vertex (Node)

An individual element in the graph. Example: A, B, C, D.

Edge

A connection between two vertices. Example: A → B.

Degree

The number of edges connected to a vertex. In a directed graph, in-degree counts incoming edges and out-degree counts outgoing edges.

    A
   / \
  B   C

Degree(A) = 2

Adjacent Vertices

Vertices directly connected by an edge. In the example above, A and B are adjacent.

Path

A sequence of vertices connected by edges. Example: A → B → D.

Cycle

A path that starts and ends at the same vertex. Example: A → B → C → A.

Connected vs Disconnected

A graph is connected if every vertex is reachable from every other vertex. Otherwise it is disconnected.

Connected:      A --- B --- C

Disconnected:   A --- B     C --- D

Types of Graphs

Graphs come in several forms, each suited to different problems.

Undirected Graph

Edges have no direction — travel is possible in both directions between any connected pair of vertices.

A ----- B    (A can reach B, B can reach A)

Directed Graph (Digraph)

Edges have a direction — an edge A → B means you can go from A to B but not necessarily back.

A → B → C
↑       |
|       ↓
E ← D ←-

Weighted Graph

Each edge carries a weight (cost, distance, time). Used in shortest path and MST algorithms.

A --5-- B
|       |
2       4
|       |
C --1-- D

Unweighted Graph

All edges are considered equal — no weights. BFS finds shortest paths in terms of edge count.

Cyclic vs Acyclic

A cyclic graph contains at least one cycle. An acyclic graph has no cycles.

Directed Acyclic Graph (DAG)

A directed graph with no cycles. Essential for topological sorting, build systems, and dependency resolution.

A
| \
v  v
B  C
 \ |
  v
  D

Complete Graph

Every vertex is connected to every other vertex. For n vertices, the number of edges is:

Edges = n(n āˆ’ 1) / 2

Bipartite Graph

Vertices are split into two disjoint sets where edges only go between the sets (never within a set). Used in matching problems and recommendation systems.

Students      Subjects

Alice ------- Math
Alice ------- Science
Bob --------- Science

Graph Representation

There are two standard ways to store a graph in memory. The right choice depends on whether the graph is sparse (few edges) or dense (many edges).

Adjacency Matrix

A 2D boolean (or weight) matrix where matrix[i][j] = 1 if there is an edge from vertex i to vertex j.

Graph:
    A
   / \
  B---C

Matrix:
     A  B  C
  A  0  1  1
  B  1  0  1
  C  1  1  0
int[][] graph = {
    {0, 1, 1},
    {1, 0, 1},
    {1, 1, 0}
};

Advantages: Simple to implement. Edge lookup is O(1).

Disadvantages: Space complexity is O(V²) — wasteful for sparse graphs.

Adjacency List

Each vertex stores a list of its neighbors. Much more memory-efficient for sparse graphs.

Graph:
A --- B
|
C

Adjacency List:
A → [B, C]
B → [A]
C → [A]
List<List<Integer>> graph = new ArrayList<>();

for (int i = 0; i < V; i++) {
    graph.add(new ArrayList<>());
}

// Add edges for undirected graph
graph.get(0).add(1); // A - B
graph.get(0).add(2); // A - C
graph.get(1).add(0); // B - A
graph.get(2).add(0); // C - A

Advantages: Space complexity O(V + E) — efficient for sparse graphs.

Disadvantages: Checking if an edge exists may require O(degree) traversal.

Matrix vs List

FeatureAdjacency MatrixAdjacency List
SpaceO(V²)O(V + E)
Edge lookupO(1)O(degree)
Add edgeO(1)O(1)
Iterate neighborsO(V)O(degree)
Best for sparse graphsPoorExcellent
Best for dense graphsGoodGood

Graph Traversal

Traversal means visiting every reachable vertex in the graph. There are two fundamental strategies:

  • BFS — Breadth First Search (level by level)
  • DFS — Depth First Search (as deep as possible first)

Both have time complexity O(V + E) and space complexity O(V).

Breadth First Search (BFS)

BFS visits all vertices at distance 1 from the source first, then distance 2, and so on. It uses a queue (FIFO) to track which vertices to visit next.

Graph:
      A
     / \
    B   C
   /
  D

BFS from A: A → B → C → D

Algorithm steps:

  1. Start at the source vertex, mark it visited, enqueue it.
  2. Dequeue the front vertex and process it.
  3. Enqueue all unvisited neighbors and mark them visited.
  4. Repeat until the queue is empty.
public void bfs(int start) {
    Queue<Integer> queue = new LinkedList<>();
    boolean[] visited = new boolean[V];

    visited[start] = true;
    queue.offer(start);

    while (!queue.isEmpty()) {
        int node = queue.poll();
        System.out.print(node + " ");

        for (int neighbor : graph.get(node)) {
            if (!visited[neighbor]) {
                visited[neighbor] = true;
                queue.offer(neighbor);
            }
        }
    }
}
ComplexityValue
TimeO(V + E)
SpaceO(V)

BFS guarantees the shortest path (in terms of edge count) in an unweighted graph.

Depth First Search (DFS)

DFS explores as far as possible along each branch before backtracking. It uses a stack — either explicit or via the call stack through recursion.

Graph:
      A
     / \
    B   C
   /
  D

DFS from A: A → B → D → C

Recursive implementation:

public void dfs(int node, boolean[] visited) {
    visited[node] = true;
    System.out.print(node + " ");

    for (int neighbor : graph.get(node)) {
        if (!visited[neighbor]) {
            dfs(neighbor, visited);
        }
    }
}

Iterative implementation using an explicit stack:

public void dfsIterative(int start) {
    Stack<Integer> stack = new Stack<>();
    boolean[] visited = new boolean[V];

    stack.push(start);

    while (!stack.isEmpty()) {
        int node = stack.pop();
        if (!visited[node]) {
            visited[node] = true;
            System.out.print(node + " ");
            for (int neighbor : graph.get(node)) {
                if (!visited[neighbor]) {
                    stack.push(neighbor);
                }
            }
        }
    }
}
ComplexityValue
TimeO(V + E)
SpaceO(V)

BFS vs DFS

FeatureBFSDFS
Data structureQueueStack / Recursion
Traversal orderLevel by levelDepth first
Shortest path (unweighted)YesNo
Memory usageHigher (wide graphs)Lower (deep graphs)
Cycle detectionYesYes
Topological sortNoYes
Connected componentsYesYes

Topological Sorting

Topological sorting produces a linear ordering of vertices in a Directed Acyclic Graph (DAG) such that for every directed edge u → v, vertex u comes before v.

DAG:
A → C
B → C
C → D

Valid topological orders:
  A B C D
  B A C D

DFS-based approach:

public void topoSort(int node,
                     boolean[] visited,
                     Stack<Integer> stack) {
    visited[node] = true;

    for (int neighbor : graph.get(node)) {
        if (!visited[neighbor]) {
            topoSort(neighbor, visited, stack);
        }
    }

    stack.push(node); // push after all descendants
}

Applications: course scheduling, build systems, dependency resolution, Git commit ordering.

Time Complexity: O(V + E)

Minimum Spanning Tree

A Spanning Tree of a graph includes all vertices connected with the minimum number of edges (exactly V āˆ’ 1 edges, no cycles). The Minimum Spanning Tree (MST) is the spanning tree with the lowest total edge weight.

Prim's Algorithm

Builds the MST by greedily adding the cheapest edge that connects a new vertex to the growing tree. Uses a priority queue.

Time Complexity: O((V + E) log V)

Kruskal's Algorithm

Sorts all edges by weight and adds them one by one, skipping any edge that would create a cycle (detected using Union-Find / Disjoint Set Union).

Time Complexity: O(E log E)

MST applications: road network design, network cable routing, electrical grid planning.

Shortest Path Algorithms

Finding the shortest path between vertices is one of the most important graph problems.

Dijkstra's Algorithm

Works with non-negative edge weights. Uses a min-heap priority queue to always expand the cheapest unvisited vertex.

public int[] dijkstra(int src) {
    int[] dist = new int[V];
    Arrays.fill(dist, Integer.MAX_VALUE);
    dist[src] = 0;

    PriorityQueue<int[]> pq =
        new PriorityQueue<>(Comparator.comparingInt(a -> a[1]));
    pq.offer(new int[]{src, 0});

    while (!pq.isEmpty()) {
        int[] curr = pq.poll();
        int node = curr[0], d = curr[1];
        if (d > dist[node]) continue;

        for (int[] edge : graph.get(node)) {
            int neighbor = edge[0], weight = edge[1];
            if (dist[node] + weight < dist[neighbor]) {
                dist[neighbor] = dist[node] + weight;
                pq.offer(new int[]{neighbor, dist[neighbor]});
            }
        }
    }
    return dist;
}

Time Complexity: O((V + E) log V)

Applications: GPS navigation, route planning, network packet routing.

Bellman-Ford Algorithm

Handles graphs with negative edge weights. Relaxes all edges V āˆ’ 1 times. Can also detect negative weight cycles.

Time Complexity: O(V Ɨ E)

Floyd-Warshall Algorithm

Finds shortest paths between all pairs of vertices using dynamic programming. Works with negative weights (but not negative cycles).

Time Complexity: O(V³)

AlgorithmNegative WeightsSingle SourceAll PairsComplexity
DijkstraNoYesNoO((V+E) log V)
Bellman-FordYesYesNoO(VE)
Floyd-WarshallYesNoYesO(V³)

Cycle Detection

Detecting whether a graph contains a cycle is important in dependency checking, deadlock detection, and validating DAGs.

Undirected Graph

Use DFS with parent tracking, or Union-Find (Disjoint Set Union). If a visited neighbor is not the parent, a cycle exists.

public boolean hasCycleUndirected(int node,
                                   int parent,
                                   boolean[] visited) {
    visited[node] = true;

    for (int neighbor : graph.get(node)) {
        if (!visited[neighbor]) {
            if (hasCycleUndirected(neighbor, node, visited))
                return true;
        } else if (neighbor != parent) {
            return true; // back edge found → cycle
        }
    }
    return false;
}

Directed Graph

Use DFS with a recursion stack. If a visited vertex is already in the current recursion stack, a cycle exists.

public boolean hasCycleDirected(int node,
                                 boolean[] visited,
                                 boolean[] recStack) {
    visited[node] = true;
    recStack[node] = true;

    for (int neighbor : graph.get(node)) {
        if (!visited[neighbor]) {
            if (hasCycleDirected(neighbor, visited, recStack))
                return true;
        } else if (recStack[neighbor]) {
            return true; // back edge → cycle
        }
    }

    recStack[node] = false;
    return false;
}

Complexity Summary

AlgorithmTime ComplexitySpace
BFSO(V + E)O(V)
DFSO(V + E)O(V)
Topological SortO(V + E)O(V)
DijkstraO((V + E) log V)O(V)
Bellman-FordO(V Ɨ E)O(V)
Floyd-WarshallO(V³)O(V²)
Prim's MSTO((V + E) log V)O(V)
Kruskal's MSTO(E log E)O(V)
Cycle DetectionO(V + E)O(V)

Applications of Graphs

Graphs power some of the most important systems in computing:

Social Networks

Users are vertices, friendships or follows are edges. Used to find mutual friends, shortest social distance, and community detection.

Maps and Navigation

Cities are vertices, roads are weighted edges. Dijkstra's and A* algorithms find optimal routes.

Internet and Networking

Routers are vertices, connections are edges. Routing protocols use shortest path algorithms to forward packets efficiently.

Compiler Design

Dependency graphs determine compilation order. Topological sort ensures each module is compiled after its dependencies.

Operating Systems

Resource Allocation Graphs detect deadlocks. A cycle in this graph means a deadlock exists.

Recommendation Systems

Bipartite graphs model users and items. Graph traversal identifies what similar users liked.

Artificial Intelligence

State space graphs represent all possible states of a problem. BFS and DFS power search algorithms like A* pathfinding.

Common Interview Questions

Easy

  1. What is a Graph? How is it different from a Tree?
  2. What is the degree of a vertex?
  3. What is the difference between directed and undirected graphs?
  4. What is a cycle in a graph?

Medium

  1. Implement BFS and DFS for an adjacency list.
  2. Detect a cycle in an undirected graph.
  3. Detect a cycle in a directed graph.
  4. Count connected components in a graph.
  5. Find the number of islands (LeetCode 200).
  6. Perform topological sort on a DAG.

Hard

  1. Dijkstra's shortest path algorithm.
  2. Bellman-Ford with negative weight detection.
  3. Kruskal's or Prim's MST algorithm.
  4. Strongly Connected Components (Kosaraju / Tarjan).
  5. Shortest path in a grid with obstacles.
  6. Word Ladder problem (BFS on implicit graph).

Revision Summary

A Graph is a non-linear data structure made of vertices and edges used to model relationships between objects.

Key Types

  • Directed / Undirected
  • Weighted / Unweighted
  • Cyclic / Acyclic
  • DAG (Directed Acyclic Graph)
  • Complete and Bipartite graphs

Representation

  • Adjacency Matrix → O(V²) space, O(1) edge lookup
  • Adjacency List → O(V + E) space, preferred for sparse graphs

Core Traversals

  • BFS — Queue — shortest path in unweighted graphs
  • DFS — Stack/Recursion — cycle detection, topological sort

Must-Know Algorithms

  • BFS and DFS
  • Topological Sort (Kahn's BFS or DFS-based)
  • Dijkstra (non-negative weights)
  • Bellman-Ford (negative weights)
  • Floyd-Warshall (all-pairs shortest path)
  • Prim and Kruskal (Minimum Spanning Tree)
  • Cycle Detection (DFS with parent / recursion stack)

Graphs are among the most important topics in DSA. They model real-world problems in networking, navigation, scheduling, AI, and social systems — and appear frequently in coding interviews at every level.