Last Updated: 23 January, 2025 5 Mins
In graph data structure, the process of storing a graph in the memory of a computer is referred to as a graph representation.
A graph in a data structure can be represented in many ways. The two most common and popular ways to represent a graph are:
Adjacency Matrix
Adjacency List
In this tutorial, we will learn all about Adjacency Matrix in details with example in Java.
An adjacency matrix represents a graph using a 2D array. A 2D array is a tabular format that consists of rows and columns. Each cell in the matrix indicates whether an edge exists between two vertices. If there is a connection between two vertices, the cell contains a value (usually 1 for unweighted graphs or the weight of the edge for weighted graphs); otherwise, it contains 0.
Consider a graph with n numbers of vertices. Create a 2D matrix adjMatrix[n][n] having dimension n x n.
Adjacency Matrix Representation of Undirected Graph
A undirected graph is given below, which has 4 vertices (A, B, C, D), and the edges are: (A-B), (A-C), (B-D), and (C-D).
In the adjacency matrix table, both rows and columns are representing the nodes. If two nodes are connected to each other, we store the value 1 in the cell where the row and column both are meeting; otherwise, we store value 0 in that cell, which means there is no connection between the two nodes.
Output
Adjacency Matrix Elements: 0 1 1 0 1 0 1 0 1 1 0 1 0 0 1 0
That's all, guys. I hope this article is helpful for you.
Happy Learning... 😀
feedback@javabytechie.com