Open In App

Adjacency Matrix

Last Updated : 29 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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. An adjacency matrix is a simple and straightforward way to represent graphs and is particularly useful for dense graphs.

Adjacency-Matrix

What is Adjacency Matrix?

Adjacency Matrix is a square matrix used to represent a finite graph by storing the relationships between the nodes in their respective cells. For a graph with V vertices, the adjacency matrix A is an V X V matrix where:

  • A[i][j] = 1, if there is an edge between vertex i and vertex j
  • A[i][j] = 0, if there is no edge between vertex i and vertex j

1. Adjacency Matrix for Undirected and Unweighted graph:

Consider an Undirected and Unweighted graph G with 4 vertices and 3 edges. For the graph G, the adjacency matrix would look like:

Adjacency-Matrix-for-Undirected-and-Unweighted-graph

Here’s how to interpret the matrix:

  • A[0][1] ​= 1, there is an edge between vertex 0 and vertex 1.
  • A[1][0] ​= 1, there is an edge between vertex 1 and vertex 0.
  • A[1][2] ​= 1, there is an edge between vertex 1 and vertex 2.
  • A[2][1] ​= 1, there is an edge between vertex 2 and vertex 1.
  • A[2][3] = 1, there is an edge between vertex 2 and vertex 3.
  • A[3][2] = 1, there is an edge between vertex 3 and vertex 2.
  • A[i][i] = 0, as there are no self loops on the graph.
  • All other entries with a value of 0 indicate no edge between the corresponding vertices.

2. Adjacency Matrix for Undirected and Weighted graph:

Consider an Undirected and Weighted graph G with 5 vertices and 5 edges. For the graph G, the adjacency matrix would look like:

Adjacency-Matrix-for-Undirected-and-Weighted-graph

Here’s how to interpret the matrix:

  • A[0][1] ​= 5, there is an edge between vertex 0 and vertex 1 having weight = 5.
  • A[1][0] ​= 5, there is an edge between vertex 1 and vertex 0 having weight = 5.
  • A[1][2] ​= 7, there is an edge between vertex 1 and vertex 2 having weight = 7.
  • A[2][1] ​= 7, there is an edge between vertex 2 and vertex 1 having weight = 7.
  • A[2][3] ​= 3, there is an edge between vertex 2 and vertex 3 having weight = 3.
  • A[3][2] ​= 3, there is an edge between vertex 3 and vertex 2 having weight = 3.
  • A[1][3] = 10, there is an edge between vertex 1 and vertex 3 having weight = 10.
  • A[3][1] = 10, there is an edge between vertex 3 and vertex 1 having weight = 10.
  • A[3][4] = 6, there is an edge between vertex 3 and vertex 4 having weight = 6.
  • A[4][3] = 6, there is an edge between vertex 4 and vertex 3 having weight = 6.
  • A[i][i] = INF, as there are no self loops on the graph. We can also initialize A[i][i] = 0 as starting from any node i, we don’t need to traverse any edge to reach node i.
  • All other entries with a value of INF indicate no edge between the corresponding vertices.

3. Adjacency Matrix for Directed and Unweighted graph:

Consider an Directed and Unweighted graph G with 4 vertices and 4 edges. For the graph G, the adjacency matrix would look like:

Adjacency-Matrix-for-Directed-and-Unweighted-graph

Here’s how to interpret the matrix:

  • A[0][1] ​= 1, there is an edge between vertex 0 and vertex 1.
  • A[1][2] ​= 1, there is an edge between vertex 1 and vertex 2.
  • A[2][3] = 1, there is an edge between vertex 2 and vertex 3.
  • A[3][1] = 1, there is an edge between vertex 3 and vertex 1.
  • A[i][i] = 0, as there are no self loops on the graph.
  • All other entries with a value of 0 indicate no edge between the corresponding vertices.

4. Adjacency Matrix for Directed and Weighted graph:

Consider an Directed and Weighted graph G with 5 vertices and 6 edges. For the graph G, the adjacency matrix would look like:

Adjacency-Matrix-for-Directed-and-Weighted-graph

Here’s how to interpret the matrix:

  • A[0][1] ​= 1, there is an edge between vertex 0 and vertex 1.
  • A[1][2] ​= 1, there is an edge between vertex 1 and vertex 2.
  • A[2][3] = 1, there is an edge between vertex 2 and vertex 3.
  • A[3][1] = 1, there is an edge between vertex 3 and vertex 1.
  • A[i][i] = 0, as there are no self loops on the graph.
  • All other entries with a value of 0 indicate no edge between the corresponding vertices.

Implementation of Adjacency Matrix:

Below is a program to create an adjacency matrix for an undirected graph:

C++
#include <iostream>
#include <vector>

using namespace std;

vector<vector<int> >
createAdjacencyMatrix(vector<vector<int> >& graph,
                      int numVertices)
{
    // Initialize the adjacency matrix with zeros
    vector<vector<int> > adjMatrix(
        numVertices, vector<int>(numVertices, 0));

    // Fill the adjacency matrix based on the edges in the
    // graph
    for (int i = 0; i < numVertices; ++i) {
        for (int j = 0; j < numVertices; ++j) {
            if (graph[i][j] == 1) {
                adjMatrix[i][j] = 1;
                adjMatrix[j][i]
                    = 1; // For undirected graph, set
                         // symmetric entries
            }
        }
    }

    return adjMatrix;
}

int main()
{
    // Example graph represented as an adjacency list
    // The indices represent the vertices, and the values
    // are lists of neighboring vertices
    vector<vector<int> > graph = { { 0, 1, 0, 0 },
                                   { 1, 0, 1, 0 },
                                   { 0, 1, 0, 1 },
                                   { 0, 0, 1, 0 } };

    int numVertices = graph.size();

    // Create the adjacency matrix
    vector<vector<int> > adjMatrix
        = createAdjacencyMatrix(graph, numVertices);

    // Print the adjacency matrix
    for (int i = 0; i < numVertices; ++i) {
        for (int j = 0; j < numVertices; ++j) {
            cout << adjMatrix[i][j] << " ";
        }
        cout << endl;
    }

    return 0;
}
Java
import java.util.ArrayList;
import java.util.Arrays;

public class AdjacencyMatrix {
    public static int[][] createAdjacencyMatrix(
        ArrayList<ArrayList<Integer> > graph,
        int numVertices)
    {
        // Initialize the adjacency matrix with zeros
        int[][] adjMatrix
            = new int[numVertices][numVertices];

        // Fill the adjacency matrix based on the edges in
        // the graph
        for (int i = 0; i < numVertices; ++i) {
            for (int j = 0; j < numVertices; ++j) {
                if (graph.get(i).get(j) == 1) {
                    adjMatrix[i][j] = 1;
                    adjMatrix[j][i]
                        = 1; // For undirected graph, set
                             // symmetric entries
                }
            }
        }

        return adjMatrix;
    }

    public static void main(String[] args)
    {
        // Example graph represented as an adjacency list
        // The indices represent the vertices, and the
        // values are lists of neighboring vertices
        ArrayList<ArrayList<Integer> > graph
            = new ArrayList<>();
        graph.add(
            new ArrayList<>(Arrays.asList(0, 1, 0, 0)));
        graph.add(
            new ArrayList<>(Arrays.asList(1, 0, 1, 0)));
        graph.add(
            new ArrayList<>(Arrays.asList(0, 1, 0, 1)));
        graph.add(
            new ArrayList<>(Arrays.asList(0, 0, 1, 0)));

        int numVertices = graph.size();

        // Create the adjacency matrix
        int[][] adjMatrix
            = createAdjacencyMatrix(graph, numVertices);

        // Print the adjacency matrix
        for (int i = 0; i < numVertices; ++i) {
            for (int j = 0; j < numVertices; ++j) {
                System.out.print(adjMatrix[i][j] + " ");
            }
            System.out.println();
        }
    }
}

// This code is contributed by shivamgupta310570
Python3
def create_adjacency_matrix(graph):
    # Get the number of vertices in the graph
    num_vertices = len(graph)

    # Initialize the adjacency matrix with zeros
    adj_matrix = [[0] * num_vertices for _ in range(num_vertices)]

    # Fill the adjacency matrix based on the edges in the graph
    for i in range(num_vertices):
        for j in range(num_vertices):
            if graph[i][j] == 1:
                adj_matrix[i][j] = 1
                # For undirected graph, set symmetric entries
                adj_matrix[j][i] = 1

    return adj_matrix


# Example graph represented as an adjacency list
# The indices represent the vertices, and the values are lists of neighboring vertices
graph = [
    [0, 1, 0, 0],
    [1, 0, 1, 0],
    [0, 1, 0, 1],
    [0, 0, 1, 0]
]

# Create the adjacency matrix
adj_matrix = create_adjacency_matrix(graph)

# Print the adjacency matrix
for row in adj_matrix:
    print(' '.join(map(str, row)))

# This code is contributed by shivamgupta0987654321
JavaScript
function createAdjacencyMatrix(graph) {
    const numVertices = graph.length;

    // Initialize the adjacency matrix with zeros
    const adjMatrix = Array.from(Array(numVertices), () => Array(numVertices).fill(0));

    // Fill the adjacency matrix based on the edges in the graph
    for (let i = 0; i < numVertices; ++i) {
        for (let j = 0; j < numVertices; ++j) {
            if (graph[i][j] === 1) {
                adjMatrix[i][j] = 1;
                adjMatrix[j][i] = 1; // For undirected graph, set symmetric entries
            }
        }
    }

    return adjMatrix;
}

// Example graph represented as an adjacency list
// The indices represent the vertices, and the values are lists of neighboring vertices
const graph = [
    [0, 1, 0, 0],
    [1, 0, 1, 0],
    [0, 1, 0, 1],
    [0, 0, 1, 0]
];

// Create the adjacency matrix
const adjMatrix = createAdjacencyMatrix(graph);

// Print the adjacency matrix
for (let i = 0; i < adjMatrix.length; ++i) {
    console.log(adjMatrix[i].join(' '));
}

Output
0 1 0 0 
1 0 1 0 
0 1 0 1 
0 0 1 0 

Properties of Adjacency Matrix:

  • Diagonal Entries: The diagonal entries A[i][i] are usually set to 0, assuming the graph has no self-loops.
  • Undirected Graphs: For undirected graphs, the adjacency matrix is symmetric. This means A[i][j] ​= A[j][i]​ for all i and j.
  • Weighted Graphs: The adjacency matrix can also be used to represent weighted graphs by storing the weight of the edge instead of 1 or 0.

Applications of Adjacency Matrix:

  • Graph Representation: The adjacency matrix is one of the most common ways to represent a graph computationally.
  • Connectivity: By examining the entries of the adjacency matrix, one can determine whether the graph is connected or not. If the graph is undirected, it is connected if and only if the corresponding adjacency matrix is irreducible (i.e., there is a path between every pair of vertices). In directed graphs, connectivity can be analyzed using concepts like strongly connected components.
  • Degree of Vertices: The degree of a vertex in a graph is the number of edges incident to it. In an undirected graph, the degree of a vertex can be calculated by summing the entries in the corresponding row (or column) of the adjacency matrix. In a directed graph, the in-degree and out-degree of a vertex can be similarly determined.

Advantages of Adjacency Matrix:

  • Simple: Simple and Easy to implement.
  • Space Efficient for Dense Graphs: Space efficient when the graph is dense as it requires V * V space to represent the entire graph.
  • Faster access to Edges: Adjacency Matrix allows constant look up to check whether there exists an edge between a pair of vertices.

Disadvantages of Adjacency Matrix:

  • Space inefficient for Sparse Graphs: Takes up O(V* V) space even if the graph is sparse.
  • Costly Insertions and Deletions: Adding or deleting a vertex can be costly as it requires resizing the matrix.
  • Slow Traversals: Graph traversals like DFS, BFS takes O(V * V) time to visit all the vertices whereas Adjacency List takes only O(V + E).


Similar Reads

Convert Adjacency Matrix to Adjacency List representation of Graph
Prerequisite: Graph and its representations Given a adjacency matrix representation of a Graph. The task is to convert the given Adjacency Matrix to Adjacency List representation. Examples: Input: arr[][] = [ [0, 0, 1], [0, 0, 1], [1, 1, 0] ] Output: The adjacency list is: 0 -&gt; 2 1 -&gt; 2 2 -&gt; 0 -&gt; 1Input: arr[][] = [ [0, 1, 0, 0, 1], [1,
6 min read
Comparison between Adjacency List and Adjacency Matrix representation of Graph
A Graph is a non-linear data structure consisting of nodes and edges. The nodes are sometimes also referred to as vertices and the edges are lines or arcs that connect any two nodes in the graph. In this article, we will understand the difference between the ways of representation of the graph. A graph can be represented in mainly two ways. They ar
4 min read
Convert Adjacency List to Adjacency Matrix representation of a Graph
Given an adjacency list representation of a Graph, the task is to convert the given Adjacency List to Adjacency Matrix representation. Examples: Input: adjList[] = {{0 --&gt; 1 --&gt; 3}, {1 --&gt; 2}, {2 --&gt; 3}} Output: 0 1 0 10 0 1 00 0 0 10 0 0 0 Input: adjList[] = {{0 --&gt; 1 --&gt; 4}, {1 --&gt; 0 --&gt; 2 --&gt; 3 --&gt; 4}, {2 --&gt; 1 -
9 min read
Prim's Algorithm (Simple Implementation for Adjacency Matrix Representation)
We have discussed Prim's algorithm and its implementation for adjacency matrix representation of graphs. As discussed in the previous post, in Prim's algorithm, two sets are maintained, one set contains list of vertices already included in MST, other set contains vertices not yet included. In every iteration, we consider the minimum weight edge amo
9 min read
Kruskal's Algorithm (Simple Implementation for Adjacency Matrix)
Below are the steps for finding MST using Kruskal's algorithm Sort all the edges in non-decreasing order of their weight. Pick the smallest edge. Check if it forms a cycle with the spanning tree formed so far. If cycle is not formed, include this edge. Else, discard it. Repeat step#2 until there are (V-1) edges in the spanning tree. We have discuss
9 min read
Implementation of DFS using adjacency matrix
Depth First Search (DFS) has been discussed in this article which uses adjacency list for the graph representation. In this article, adjacency matrix will be used to represent the graph.Adjacency matrix representation: In adjacency matrix representation of a graph, the matrix mat[][] of size n*n (where n is the number of vertices) will represent th
8 min read
Implementation of BFS using adjacency matrix
Breadth First Search (BFS) has been discussed in this article which uses adjacency list for the graph representation. In this article, adjacency matrix will be used to represent the graph. Adjacency matrix representation: In adjacency matrix representation of a graph, the matrix mat[][] of size n*n (where n is the number of vertices) will represent
7 min read
Add and Remove vertex in Adjacency Matrix representation of Graph
A graph is a presentation of a set of entities where some pairs of entities are linked by a connection. Interconnected entities are represented by points referred to as vertices, and the connections between the vertices are termed as edges. Formally, a graph is a pair of sets (V, E), where V is a collection of vertices, and E is a collection of edg
15+ min read
C program to implement Adjacency Matrix of a given Graph
Given a undirected Graph of N vertices 1 to N and M edges in form of 2D array arr[][] whose every row consists of two numbers X and Y which denotes that there is a edge between X and Y, the task is to write C program to create Adjacency Matrix of the given Graph. Examples: Input: N = 5, M = 4, arr[][] = { { 1, 2 }, { 2, 3 }, { 4, 5 }, { 1, 5 } } Ou
3 min read
Add and Remove Edge in Adjacency Matrix representation of a Graph
Prerequisites: Graph and its representationsGiven an adjacency matrix g[][] of a graph consisting of N vertices, the task is to modify the matrix after insertion of all edges[] and removal of edge between vertices (X, Y). In an adjacency matrix, if an edge exists between vertices i and j of the graph, then g[i][j] = 1 and g[j][i] = 1. If no edge ex
13 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg