codingstuff.io
ExploreTutorialsProblemsCS Subjects
Get Started
ExploreTutorialsProblemsCS Subjects
Get Started
codingstuff.io

Master the art of building software through interactive tutorials, real-world problems, and guided projects.

Pune, Maharashtra, India

codingstuffmail@gmail.com

Product

  • Explore
  • Tutorials
  • Problems
  • CS Subjects

Company

  • About
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Sitemap

© 2026 codingstuff.io. All rights reserved.

Built with ❤️ for developers everywhere

/
/
All Tutorials
🧮

Data Structures & Algorithms

19 / 65 topics
13Binary Search Trees (BSTs)14Balanced Binary Search Trees15AVL Trees16Red-Black Trees17B-Trees18Graphs Basics19Graph Representations (Adjacency List, Matrix)64AVL Trees Advantages and Disadvantages65Red-Black Trees Advantages and Disadvantages
Tutorials/Data Structures & Algorithms/Graph Representations (Adjacency List, Matrix)
🧮Data Structures & Algorithms

Graph Representations (Adjacency List, Matrix)

Updated 2026-04-20
3 min read

Graph Representations (Adjacency List, Matrix)

Introduction

Graphs are a fundamental data structure used to model pairwise relationships between objects. They consist of nodes (also known as vertices) and edges that connect these nodes. Understanding how to represent graphs is crucial for implementing various graph algorithms efficiently.

In this tutorial, we will explore two common ways to represent graphs: Adjacency List and Adjacency Matrix. Each representation has its own advantages and use cases, and choosing the right one can significantly impact the performance of your graph-related applications.

Adjacency List

Definition

An adjacency list is a collection of unordered lists used to represent a finite graph. Each list describes the set of neighbors of a vertex in the graph.

Structure

  • Vertices: Each vertex has a list of adjacent vertices.
  • Edges: The edges are implicitly represented by the presence of an adjacent vertex in another's list.

Advantages

  1. Space Efficiency: Saves space for sparse graphs (graphs with few edges).
  2. Fast Iteration: Allows for efficient iteration over all neighbors of a vertex.
  3. Dynamic Nature: Easy to add or remove vertices and edges.

Disadvantages

  1. Slow Edge Queries: Checking if an edge exists between two vertices can be slow compared to an adjacency matrix.
  2. Complexity in Certain Algorithms: Some graph algorithms may require random access to edges, which is not efficient with an adjacency list.

Implementation

Here's a simple implementation of an adjacency list using Python:

class Graph:
    def __init__(self):
        self.adj_list = {}

    def add_vertex(self, vertex):
        if vertex not in self.adj_list:
            self.adj_list[vertex] = []

    def add_edge(self, v1, v2):
        if v1 in self.adj_list and v2 in self.adj_list:
            self.adj_list[v1].append(v2)
            self.adj_list[v2].append(v1)

    def remove_edge(self, v1, v2):
        if v1 in self.adj_list and v2 in self.adj_list:
            self.adj_list[v1].remove(v2)
            self.adj_list[v2].remove(v1)

    def remove_vertex(self, vertex):
        if vertex in self.adj_list:
            for other_vertex in self.adj_list[vertex]:
                self.adj_list[other_vertex].remove(vertex)
            del self.adj_list[vertex]

    def print_graph(self):
        for vertex in self.adj_list:
            print(f"{vertex} -> {self.adj_list[vertex]}")

# Example usage
graph = Graph()
graph.add_vertex("A")
graph.add_vertex("B")
graph.add_edge("A", "B")
graph.print_graph()  # Output: A -> ['B']\nB -> ['A']

Adjacency Matrix

Definition

An adjacency matrix is a square matrix used to represent a finite graph. The elements of the matrix indicate whether pairs of vertices are adjacent or not in the graph.

Structure

  • Vertices: Rows and columns represent vertices.
  • Edges: A value of 1 indicates an edge between two vertices, while a value of 0 indicates no edge.

Advantages

  1. Fast Edge Queries: Checking if an edge exists between two vertices is very fast (O(1)).
  2. Simpler Implementation for Some Algorithms: Certain graph algorithms are simpler to implement with an adjacency matrix.
  3. Random Access: Allows for easy random access to edges.

Disadvantages

  1. Space Inefficient: Uses more space, especially for sparse graphs.
  2. Slow Iteration: Iterating over all neighbors of a vertex can be slower compared to an adjacency list.

Implementation

Here's a simple implementation of an adjacency matrix using Python:

class Graph:
    def __init__(self, num_vertices):
        self.num_vertices = num_vertices
        self.adj_matrix = [[0 for _ in range(num_vertices)] for _ in range(num_vertices)]

    def add_edge(self, v1, v2):
        if 0 <= v1 < self.num_vertices and 0 <= v2 < self.num_vertices:
            self.adj_matrix[v1][v2] = 1
            self.adj_matrix[v2][v1] = 1

    def remove_edge(self, v1, v2):
        if 0 <= v1 < self.num_vertices and 0 <= v2 < self.num_vertices:
            self.adj_matrix[v1][v2] = 0
            self.adj_matrix[v2][v1] = 0

    def print_graph(self):
        for row in self.adj_matrix:
            print(row)

# Example usage
graph = Graph(3)
graph.add_edge(0, 1)
graph.print_graph()  # Output: [0, 1, 0]\n[1, 0, 0]\n[0, 0, 0]

Choosing the Right Representation

The choice between an adjacency list and an adjacency matrix depends on the specific requirements of your application:

  • Use an Adjacency List when:

    • The graph is sparse.
    • You need to frequently iterate over neighbors of a vertex.
    • You require dynamic changes to the graph (adding/removing vertices/edges).
  • Use an Adjacency Matrix when:

    • The graph is dense.
    • Fast edge queries are critical.
    • Random access to edges is needed.

Best Practices

  1. Consider Graph Density: Always consider whether your graph is sparse or dense before choosing a representation.
  2. Optimize for Operations: Think about which operations you will perform most frequently and choose the representation that optimizes those operations.
  3. Use Libraries: For large-scale applications, consider using well-optimized libraries like NetworkX in Python, which provide robust implementations of both adjacency list and matrix representations.

Conclusion

Understanding graph representations is essential for efficiently implementing graph algorithms. Both adjacency lists and matrices have their strengths and weaknesses, and choosing the right one can significantly impact the performance of your application. By considering the specific requirements of your use case, you can select the most appropriate representation to optimize your graph-related tasks.


PreviousGraphs BasicsNext Depth-First Search (DFS)

Recommended Gear

Graphs BasicsDepth-First Search (DFS)