Graph and its representations
Last Updated :
23 Jul, 2025
A Graph is a non-linear data structure consisting of vertices and edges. The vertices are sometimes also referred to as nodes and the edges are lines or arcs that connect any two nodes in the graph. More formally a Graph is composed of a set of vertices( V ) and a set of edges( E ). The graph is denoted by G(V, E).
Representations of Graph
Here are the two most common ways to represent a graph : For simplicity, we are going to consider only unweighted graphs in this post.
- Adjacency Matrix
- Adjacency List
Adjacency Matrix Representation
An adjacency matrix is a way of representing a graph as a matrix of boolean (0's and 1's)
Let's assume there are n vertices in the graph So, create a 2D matrix adjMat[n][n] having dimension n x n.
- If there is an edge from vertex i to j, mark adjMat[i][j] as 1.
- If there is no edge from vertex i to j, mark adjMat[i][j] as 0.
Representation of Undirected Graph as Adjacency Matrix:
The below figure shows an undirected graph. Initially, the entire Matrix is initialized to 0. If there is an edge from source to destination, we insert 1 to both cases (adjMat[source][destination] and adjMat[destination][source]) because we can go either way.
Undirected Graph to Adjacency Matrix
C++
// C++ program to demonstrate Adjacency Matrix
// representation of undirected and unweighted graph
#include <bits/stdc++.h>
using namespace std;
void addEdge(vector<vector<int>> &mat, int i, int j)
{
mat[i][j] = 1;
mat[j][i] = 1; // Since the graph is undirected
}
void displayMatrix(vector<vector<int>> &mat)
{
int V = mat.size();
for (int i = 0; i < V; i++)
{
for (int j = 0; j < V; j++)
cout << mat[i][j] << " ";
cout << endl;
}
}
int main()
{
// Create a graph with 4 vertices and no edges
// Note that all values are initialized as 0
int V = 4;
vector<vector<int>> mat(V, vector<int>(V, 0));
// Now add edges one by one
addEdge(mat, 0, 1);
addEdge(mat, 0, 2);
addEdge(mat, 1, 2);
addEdge(mat, 2, 3);
/* Alternatively we can also create using below
code if we know all edges in advacem
vector<vector<int>> mat = {{ 0, 1, 0, 0 },
{ 1, 0, 1, 0 },
{ 0, 1, 0, 1 },
{ 0, 0, 1, 0 } }; */
cout << "Adjacency Matrix Representation" << endl;
displayMatrix(mat);
return 0;
}
C
#include<stdio.h>
#define V 4
void addEdge(int mat[V][V], int i, int j) {
mat[i][j] = 1;
mat[j][i] = 1; // Since the graph is undirected
}
void displayMatrix(int mat[V][V]) {
for (int i = 0; i < V; i++) {
for (int j = 0; j < V; j++)
printf("%d ", mat[i][j]);
printf("\n");
}
}
int main() {
// Create a graph with 4 vertices and no edges
// Note that all values are initialized as 0
int mat[V][V] = {0};
// Now add edges one by one
addEdge(mat, 0, 1);
addEdge(mat, 0, 2);
addEdge(mat, 1, 2);
addEdge(mat, 2, 3);
/* Alternatively, we can also create using the below
code if we know all edges in advance
int mat[V][V] = {
{0, 1, 0, 0},
{1, 0, 1, 0},
{0, 1, 0, 1},
{0, 0, 1, 0}
}; */
printf("Adjacency Matrix Representation\n");
displayMatrix(mat);
return 0;
}
Java
import java.util.Arrays;
public class GfG {
public static void addEdge(int[][] mat, int i, int j) {
mat[i][j] = 1;
mat[j][i] = 1; // Since the graph is undirected
}
public static void displayMatrix(int[][] mat) {
for (int[] row : mat) {
for (int val : row) {
System.out.print(val + " ");
}
System.out.println();
}
}
public static void main(String[] args) {
// Create a graph with 4 vertices and no edges
// Note that all values are initialized as 0
int V = 4;
int[][] mat = new int[V][V];
// Now add edges one by one
addEdge(mat, 0, 1);
addEdge(mat, 0, 2);
addEdge(mat, 1, 2);
addEdge(mat, 2, 3);
/* Alternatively we can also create using below
code if we know all edges in advance
int[][] mat = {{ 0, 1, 0, 0 },
{ 1, 0, 1, 0 },
{ 0, 1, 0, 1 },
{ 0, 0, 1, 0 } }; */
System.out.println("Adjacency Matrix Representation");
displayMatrix(mat);
}
}
Python
def add_edge(mat, i, j):
# Add an edge between two vertices
mat[i][j] = 1 # Graph is
mat[j][i] = 1 # Undirected
def display_matrix(mat):
# Display the adjacency matrix
for row in mat:
print(" ".join(map(str, row)))
# Main function to run the program
if __name__ == "__main__":
V = 4 # Number of vertices
mat = [[0] * V for _ in range(V)]
# Add edges to the graph
add_edge(mat, 0, 1)
add_edge(mat, 0, 2)
add_edge(mat, 1, 2)
add_edge(mat, 2, 3)
# Optionally, initialize matrix directly
"""
mat = [
[0, 1, 0, 0],
[1, 0, 1, 0],
[0, 1, 0, 1],
[0, 0, 1, 0]
]
"""
# Display adjacency matrix
print("Adjacency Matrix:")
display_matrix(mat)
C#
using System;
public class GfG
{
// Add an edge between two vertices
public static void AddEdge(int[,] mat, int i, int j)
{
mat[i, j] = 1; // Since the graph is
mat[j, i] = 1; // undirected
}
// Display the adjacency matrix
public static void DisplayMatrix(int[,] mat)
{
int V = mat.GetLength(0);
for (int i = 0; i < V; i++)
{
for (int j = 0; j < V; j++)
{
Console.Write(mat[i, j] + " ");
}
Console.WriteLine();
}
}
// Main method to run the program
public static void Main(string[] args)
{
int V = 4; // Number of vertices
int[,] mat = new int[V, V]; // Initialize matrix
// Add edges to the graph
AddEdge(mat, 0, 1);
AddEdge(mat, 0, 2);
AddEdge(mat, 1, 2);
AddEdge(mat, 2, 3);
// Optionally, initialize matrix directly
/*
int[,] mat = new int[,]
{
{ 0, 1, 0, 0 },
{ 1, 0, 1, 0 },
{ 0, 1, 0, 1 },
{ 0, 0, 1, 0 }
};
*/
// Display adjacency matrix
Console.WriteLine("Adjacency Matrix:");
DisplayMatrix(mat);
}
}
JavaScript
function addEdge(mat, i, j) {
mat[i][j] = 1; // Graph is
mat[j][i] = 1; // undirected
}
function displayMatrix(mat) {
// Display the adjacency matrix
for (const row of mat) {
console.log(row.join(" "));
}
}
// Main function to run the program
const V = 4; // Number of vertices
// Initialize matrix
let mat = Array.from({ length: V }, () => Array(V).fill(0));
// Add edges to the graph
addEdge(mat, 0, 1);
addEdge(mat, 0, 2);
addEdge(mat, 1, 2);
addEdge(mat, 2, 3);
/* Optionally, initialize matrix directly
let mat = [
[0, 1, 0, 0],
[1, 0, 1, 0],
[0, 1, 0, 1],
[0, 0, 1, 0]
];
*/
// Display adjacency matrix
console.log("Adjacency Matrix:");
displayMatrix(mat);
OutputAdjacency Matrix Representation
0 1 1 0
1 0 1 0
1 1 0 1
0 0 1 0
Representation of Directed Graph as Adjacency Matrix:
The below figure shows a directed graph. Initially, the entire Matrix is initialized to 0. If there is an edge from source to destination, we insert 1 for that particular adjMat[source][destination].
Directed Graph to Adjacency MatrixPlease refer Adjacency Matrix Representation for more details.
Adjacency List Representation
An array of Lists is used to store edges between two vertices. The size of array is equal to the number of vertices (i.e, n). Each index in this array represents a specific vertex in the graph. The entry at the index i of the array contains a linked list containing the vertices that are adjacent to vertex i. Let's assume there are n vertices in the graph So, create an array of list of size n as adjList[n].
- adjList[0] will have all the nodes which are connected (neighbour) to vertex 0.
- adjList[1] will have all the nodes which are connected (neighbour) to vertex 1 and so on.
Representation of Undirected Graph as Adjacency list:
The below undirected graph has 3 vertices. So, an array of list will be created of size 3, where each indices represent the vertices. Now, vertex 0 has two neighbours (i.e, 1 and 2). So, insert vertex 1 and 2 at indices 0 of array. Similarly, For vertex 1, it has two neighbour (i.e, 2 and 0) So, insert vertices 2 and 0 at indices 1 of array. Similarly, for vertex 2, insert its neighbours in array of list.
Undirected Graph to Adjacency list
C++
#include <iostream>
#include <vector>
using namespace std;
// Function to add an edge between two vertices
void addEdge(vector<vector<int>>& adj, int i, int j) {
adj[i].push_back(j);
adj[j].push_back(i); // Undirected
}
// Function to display the adjacency list
void displayAdjList(const vector<vector<int>>& adj) {
for (int i = 0; i < adj.size(); i++) {
cout << i << ": "; // Print the vertex
for (int j : adj[i]) {
cout << j << " "; // Print its adjacent
}
cout << endl;
}
}
// Main function
int main() {
// Create a graph with 4 vertices and no edges
int V = 4;
vector<vector<int>> adj(V);
// Now add edges one by one
addEdge(adj, 0, 1);
addEdge(adj, 0, 2);
addEdge(adj, 1, 2);
addEdge(adj, 2, 3);
cout << "Adjacency List Representation:" << endl;
displayAdjList(adj);
return 0;
}
C
#include <stdio.h>
#include <stdlib.h>
// Structure for a node in the adjacency list
struct Node {
int data;
struct Node* next;
};
// Function to create a new node
struct Node* createNode(int data) {
struct Node* newNode =
(struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = NULL;
return newNode;
}
// Function to add an edge between two vertices
void addEdge(struct Node* adj[], int i, int j) {
struct Node* newNode = createNode(j);
newNode->next = adj[i];
adj[i] = newNode;
newNode = createNode(i); // For undirected graph
newNode->next = adj[j];
adj[j] = newNode;
}
// Function to display the adjacency list
void displayAdjList(struct Node* adj[], int V) {
for (int i = 0; i < V; i++) {
printf("%d: ", i); // Print the vertex
struct Node* temp = adj[i];
while (temp != NULL) {
printf("%d ", temp->data); // Print its adjacent
temp = temp->next;
}
printf("\n");
}
}
// Main function
int main() {
// Create a graph with 4 vertices and no edges
int V = 4;
struct Node* adj[V];
for (int i = 0; i < V; i++) {
adj[i] = NULL; // Initialize adjacency list
}
// Now add edges one by one
addEdge(adj, 0, 1);
addEdge(adj, 0, 2);
addEdge(adj, 1, 2);
addEdge(adj, 2, 3);
printf("Adjacency List Representation:\n");
displayAdjList(adj, V);
return 0;
}
Java
import java.util.ArrayList;
import java.util.List;
public class GfG {
// Method to add an edge between two vertices
public static void addEdge(List<List<Integer>> adj, int i, int j) {
adj.get(i).add(j);
adj.get(j).add(i); // Undirected
}
// Method to display the adjacency list
public static void displayAdjList(List<List<Integer>> adj) {
for (int i = 0; i < adj.size(); i++) {
System.out.print(i + ": "); // Print the vertex
for (int j : adj.get(i)) {
System.out.print(j + " "); // Print its adjacent
}
System.out.println();
}
}
// Main method
public static void main(String[] args) {
// Create a graph with 4 vertices and no edges
int V = 4;
List<List<Integer>> adj = new ArrayList<>(V);
for (int i = 0; i < V; i++) {
adj.add(new ArrayList<>());
}
// Now add edges one by one
addEdge(adj, 0, 1);
addEdge(adj, 0, 2);
addEdge(adj, 1, 2);
addEdge(adj, 2, 3);
System.out.println("Adjacency List Representation:");
displayAdjList(adj);
}
}
Python
def add_edge(adj, i, j):
adj[i].append(j)
adj[j].append(i) # Undirected
def display_adj_list(adj):
for i in range(len(adj)):
print(f"{i}: ", end="")
for j in adj[i]:
print(j, end=" ")
print()
# Create a graph with 4 vertices and no edges
V = 4
adj = [[] for _ in range(V)]
# Now add edges one by one
add_edge(adj, 0, 1)
add_edge(adj, 0, 2)
add_edge(adj, 1, 2)
add_edge(adj, 2, 3)
print("Adjacency List Representation:")
display_adj_list(adj)
C#
using System;
using System.Collections.Generic;
public class GfG
{
// Method to add an edge between two vertices
public static void AddEdge(List<List<int>> adj, int i, int j)
{
adj[i].Add(j);
adj[j].Add(i); // Undirected
}
// Method to display the adjacency list
public static void DisplayAdjList(List<List<int>> adj)
{
for (int i = 0; i < adj.Count; i++)
{
Console.Write($"{i}: "); // Print the vertex
foreach (int j in adj[i])
{
Console.Write($"{j} "); // Print its adjacent
}
Console.WriteLine();
}
}
// Main method
public static void Main(string[] args)
{
// Create a graph with 4 vertices and no edges
int V = 4;
List<List<int>> adj = new List<List<int>>(V);
for (int i = 0; i < V; i++)
adj.Add(new List<int>());
// Now add edges one by one
AddEdge(adj, 0, 1);
AddEdge(adj, 0, 2);
AddEdge(adj, 1, 2);
AddEdge(adj, 2, 3);
Console.WriteLine("Adjacency List Representation:");
DisplayAdjList(adj);
}
}
JavaScript
function addEdge(adj, i, j) {
adj[i].push(j);
adj[j].push(i); // Undirected
}
function displayAdjList(adj) {
for (let i = 0; i < adj.length; i++) {
console.log(`${i}: `);
for (const j of adj[i]) {
console.log(`${j} `);
}
console.log();
}
}
// Create a graph with 4 vertices and no edges
const V = 4;
const adj = Array.from({ length: V }, () => []);
// Now add edges one by one
addEdge(adj, 0, 1);
addEdge(adj, 0, 2);
addEdge(adj, 1, 2);
addEdge(adj, 2, 3);
console.log("Adjacency List Representation:");
displayAdjList(adj);
OutputAdjacency List Representation:
0: 1 2
1: 0 2
2: 0 1 3
3: 2
Representation of Directed Graph as Adjacency list:
The below directed graph has 3 vertices. So, an array of list will be created of size 3, where each indices represent the vertices. Now, vertex 0 has no neighbours. For vertex 1, it has two neighbour (i.e, 0 and 2) So, insert vertices 0 and 2 at indices 1 of array. Similarly, for vertex 2, insert its neighbours in array of list.

Please refer Adjacency List Representation for more details.
Introduction to Graph
Graph Representation (Adjacency Matrix)
Graph Representation (Adjacency List)
Graph and its representations
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem