Day 19: Graph Representations
Graph Representations#
Welcome to Day 19 of our 60 Days of Coding Algorithm Challenge! Today, we’ll dive deeper into various ways of representing graphs in code, exploring their pros and cons, and discussing when to use each representation.
Overview of Graph Representations#
There are several ways to represent a graph in computer memory. The choice of representation depends on the type of graph and the algorithms you plan to use. The most common representations are:
- Adjacency Matrix
- Adjacency List
- Edge List
- Incidence Matrix
Let’s explore each of these in detail.
1. Adjacency Matrix#
An adjacency matrix is a 2D array of size V x V where V is the number of vertices in the graph. The entry matrix[i][j] is 1 (or the edge weight for weighted graphs) if there is an edge from vertex i to vertex j, and 0 otherwise.
Implementation:#
1class GraphMatrix:
2 def __init__(self, num_vertices, directed=False):
3 self.num_vertices = num_vertices
4 self.directed = directed
5 self.matrix = [[0 for _ in range(num_vertices)] for _ in range(num_vertices)]
6
7 def add_edge(self, v1, v2, weight=1):
8 self.matrix[v1][v2] = weight
9 if not …Keep your momentum going
Create a free account to unlock the full lesson, all 60 days, and track your progress as you go.
- Full access to all 60 daily lessons
- Track completion and build a daily streak
- Get interview-ready, one algorithm at a time
Join 2,900+ learners · 4.8/5 average rating