NOIDATUT FREE E LEARNING PLATFORM • AKTU B.TECH

Adjacency Matrices and Adjacency List

An adjacency matrix is a 2D array used to represent a finite graph. The elements of the matrix indicate whether pairs of vertices are adjacent or not in the graph. For a graph with V vertices, the matrix is V x V, storing 1 if an edge exists and 0 othrwse


Theory & Explanation

Graph Representations: Adjacency Matrix and Adjacency List

In computer science, graphs are commonly represented in memory using two primary methods: the Adjacency Matrix and the Adjacency List. The choice of representation depends on the graph's density (number of edges) and the specific operations required.

1. Graphical Representation of Sample Graph

We will use the following undirected, unweighted graph with 4 vertices (0, 1, 2, 3) and 4 edges for our examples.

0 --- 1
| \ | \
2 --- 3

Fig 1: Sample Undirected Graph G = (V, E) with V={0,1,2,3} and E={(0,1), (0,2), (1,3), (2,3)}

2. Adjacency Matrix

An Adjacency Matrix is a 2D array (matrix) of size V x V, where V is the number of vertices in the graph. If there is an edge from vertex i to vertex j, the element adj[i][j]` is 1 (or the weight of the edge), otherwise it is 0.

  • Undirected Graph: The matrix is symmetric (adj[i][j] == adj[j][i]).
  • Directed Graph: The matrix is not necessarily symmetric; adj[i][j] = 1 means an edge exists from i to j.
  • Space Complexity: O(V2). This can be inefficient for sparse graphs.
  • Time Complexity: To check if an edge exists between i and j: O(1). To find all neighbors of i: O(V).

Adjacency Matrix for Sample Graph (Fig 1)

0 1 2 3
0 0 1 1 0
1 1 0 0 1
2 1 0 0 1
3 0 1 1 0

3. Adjacency List

An Adjacency List represents a graph as an array of linked lists (or dynamic arrays/vectors). The array index corresponds to a vertex, and the list at that index contains all its adjacent vertices.

  • Undirected Graph: For an edge (u, v), vertex v is added to u's list, and u is added to v's list.
  • Directed Graph: For an edge u → v, vertex v is added only to u's list.
  • Space Complexity: O(V + E). This is efficient for sparse graphs.
  • Time Complexity: To check if an edge exists between i and j: O(degree(i))` (in the worst case, iterate through the list). To find all neighbors of i: O(degree(i)).

Adjacency List for Sample Graph (Fig 1)

0: 1 → 2
1: 0 → 3
2: 0 → 3
3: 1 → 2

4. C Implementation

A. Adjacency Matrix (C)

#include <stdio.h>

#define V 4 // Number of vertices

// Initialize matrix with 0
void initMatrix(int matrix[V][V]) {
    for (int i = 0; i < V; i++) {
        for (int j = 0; j < V; j++) {
            matrix[i][j] = 0;
        }
    }
}

// Add edge to undirected graph
void addEdge(int matrix[V][V], int i, int j) {
    matrix[i][j] = 1;
    matrix[j][i] = 1; // Symmetric for undirected graph
}

// Print the matrix
void printMatrix(int matrix[V][V]) {
    for (int i = 0; i < V; i++) {
        for (int j = 0; j < V; j++) {
            printf("%d ", matrix[i][j]);
        }
        printf("\n");
    }
}

int main() {
    int adjMatrix[V][V];
    initMatrix(adjMatrix);

    // Add edges corresponding to Fig 1
    addEdge(adjMatrix, 0, 1);
    addEdge(adjMatrix, 0, 2);
    addEdge(adjMatrix, 1, 3);
    addEdge(adjMatrix, 2, 3);

    printf("Adjacency Matrix:\n");
    printMatrix(adjMatrix);

    return 0;
}

Expected Output (C - Matrix):

Adjacency Matrix:
0 1 1 0 
1 0 0 1 
1 0 0 1 
0 1 1 0 

B. Adjacency List (C)

#include <stdio.h>
#include <stdlib.h>

// Structure for a list node
struct Node {
    int vertex;
    struct Node next;
};

// Structure for the adjacency list
struct Graph {
    int numVertices;
    struct Node adjLists;
};

// Create a node
struct Node createNode(int v) {
    struct Node newNode = (struct Node)malloc(sizeof(struct Node));
    newNode->vertex = v;
    newNode->next = NULL;
    return newNode;
}

// Create a graph
struct Graph createGraph(int vertices) {
    struct Graph graph = (struct Graph)malloc(sizeof(struct Graph));
    graph->numVertices = vertices;
    graph->adjLists = (struct Node)malloc(vertices  sizeof(struct Node));
    for (int i = 0; i < vertices; i++)
        graph->adjLists[i] = NULL;
    return graph;
}

// Add edge to undirected graph
void addEdge(struct Graph graph, int s, int d) {
    // Add edge from s to d
    struct Node newNode = createNode(d);
    newNode->next = graph->adjLists[s];
    graph->adjLists[s] = newNode;

    // Add edge from d to s
    newNode = createNode(s);
    newNode->next = graph->adjLists[d];
    graph->adjLists[d] = newNode;
}

// Print the graph
void printGraph(struct Graph graph) {
    for (int v = 0; v < graph->numVertices; v++) {
        struct Node temp = graph->adjLists[v];
        printf("\n Vertex %d: ", v);
        while (temp) {
            printf("-> %d ", temp->vertex);
            temp = temp->next;
        }
        printf("\n");
    }
}

int main() {
    struct Graph graph = createGraph(V); // Using V from previous example

    // Add edges corresponding to Fig 1
    addEdge(graph, 0, 1);
    addEdge(graph, 0, 2);
    addEdge(graph, 1, 3);
    addEdge(graph, 2, 3);

    printf("Adjacency List Representation:");
    printGraph(graph);

    return 0;
}

Expected Output (C - List):

Adjacency List Representation:
 Vertex 0: -> 2 -> 1 

 Vertex 1: -> 3 -> 0 

 Vertex 2: -> 3 -> 0 

 Vertex 3: -> 2 -> 1 

(Note: The order of vertices in each list depends on the insertion method, here it's prepended to the list.)

5. Python Implementation

A. Adjacency Matrix (Python)

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

    def add_edge(self, u, v):
        # For undirected graph, add edge in both directions
        if 0 <= u < self.num_vertices and 0 <= v < self.num_vertices:
            self.matrix[u][v] = 1
            self.matrix[v][u] = 1

    def print_matrix(self):
        print("Adjacency Matrix:")
        for row in self.matrix:
            print(" ".join(map(str, row)))

if __name__ == "__main__":
    g = GraphMatrix(4)
    g.add_edge(0, 1)
    g.add_edge(0, 2)
    g.add_edge(1, 3)
    g.add_edge(2, 3)
    g.print_matrix()

Expected Output (Python - Matrix):

Adjacency Matrix:
0 1 1 0
1 0 0 1
1 0 0 1
0 1 1 0

B. Adjacency List (Python)

from collections import defaultdict

class GraphList:
    def __init__(self):
        # Using a dictionary of lists to represent the adjacency list
        self.adj_list = defaultdict(list)

    def add_edge(self, u, v, directed=False):
        # For undirected graph, add edge in both directions
        self.adj_list[u].append(v)
        if not directed:
            self.adj_list[v].append(u)

    def print_list(self):
        print("\nAdjacency List Representation:")
        # Sorting keys for consistent output
        for vertex in sorted(self.adj_list.keys()):
            print(f"Vertex {vertex}: {' -> '.join(map(str, sorted(self.adj_list[vertex])))}")

if __name__ == "__main__":
    g = GraphList()
    g.add_edge(0, 1)
    g.add_edge(0, 2)
    g.add_edge(1, 3)
    g.add_edge(2, 3)
    g.print_list()

Expected Output (Python - List):

Adjacency List Representation:
Vertex 0: 1 -> 2
Vertex 1: 0 -> 3
Vertex 2: 0 -> 3
Vertex 3: 1 -> 2

Diagrams

adjacency-matrices-and-adjacency-list - Diagram

adjacency-matrices-and-adjacency-list - Diagram

adjacency-matrices-and-adjacency-list - Diagram

adjacency-matrices-and-adjacency-list - Diagram

Advertisement
Advertisement