Adjacency Matrix of Directed Graph
Last Updated :
29 Apr, 2024
Adjacency Matrix of a Directed Graph is a square matrix that represents the graph in a matrix form. In a directed graph, the edges have a direction associated with them, meaning the adjacency matrix will not necessarily be symmetric.
In a directed graph, the edges have a direction associated with them, meaning the adjacency matrix will not necessarily be symmetric. The adjacency matrix A of a directed graph is defined as follows:
What is Adjacency matrix of Directed graph?
For a graph with N vertices, the adjacency matrix A is an N X N matrix where:
- A[i][j] is 1 if there is a directed edge from vertex i to vertex j.
- A[i][j]​ is 0 otherwise.
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:

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.
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:

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.
Properties of Adjacency Matrix of Directed Graph:
- Diagonal Entries: The diagonal entries Aii​ are usually set to 0, assuming the graph has no self-loops.
- Out-degree and In-degree: The number of 1's in a row i (out-degree) indicates the number of outgoing edges from vertex i, while the number of 1's in a column j (in-degree) indicates the number of incoming edges to vertex j.
Implementation of Adjacency Matrix of Directed Graph:
Below is the implementation of Adjacency Matrix of Directed Graph in different languages:
C++
#include <algorithm>
#include <iostream>
#include <unordered_map>
#include <vector>
std::vector<std::vector<int> > create_adjacency_matrix(
std::unordered_map<std::string,
std::vector<std::string> >
graph)
{
std::vector<std::string> vertices;
// Get sorted list of vertices
for (const auto& pair : graph) {
vertices.push_back(pair.first);
}
std::sort(vertices.begin(), vertices.end());
int num_vertices = vertices.size();
// Initialize the adjacency matrix with zeros
std::vector<std::vector<int> > adj_matrix(
num_vertices, std::vector<int>(num_vertices, 0));
// Fill the adjacency matrix based on the edges in the
// graph
for (int i = 0; i < num_vertices; ++i) {
for (const auto& neighbor : graph[vertices[i]]) {
int j = std::distance(
vertices.begin(),
std::find(vertices.begin(), vertices.end(),
neighbor));
adj_matrix[i][j] = 1;
}
}
return adj_matrix;
}
int main()
{
// Example graph represented as a dictionary
// The keys are the vertices and the values are lists of
// neighboring vertices
std::unordered_map<std::string,
std::vector<std::string> >
graph = { { "1", { "2" } },
{ "2", { "3" } },
{ "3", { "4" } },
{ "4", { "1" } } };
// Create the adjacency matrix
std::vector<std::vector<int> > adj_matrix
= create_adjacency_matrix(graph);
// Print the adjacency matrix
for (const auto& row : adj_matrix) {
for (int value : row) {
std::cout << value << " ";
}
std::cout << std::endl;
}
return 0;
}
Java
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
public class AdjacencyMatrix {
// Function to create an adjacency matrix from an
// adjacency list
public static int[][] createAdjacencyMatrix(
HashMap<String, List<String> > graph)
{
// Get the list of vertices sorted in ascending
// order
List<String> vertices
= new ArrayList<>(graph.keySet());
Collections.sort(vertices);
// Get the number of vertices in the graph
int numVertices = vertices.size();
// 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++) {
// Get the neighbors of the current vertex
List<String> neighbors
= graph.get(vertices.get(i));
for (String neighbor : neighbors) {
// Find the index of the neighbor in the
// sorted vertices list
int j = vertices.indexOf(neighbor);
// Set the corresponding entry in the
// adjacency matrix to 1
adjMatrix[i][j] = 1;
}
}
return adjMatrix;
}
public static void main(String[] args)
{
// Example graph represented as an adjacency list
// (unordered map)
HashMap<String, List<String> > graph
= new HashMap<>();
graph.put("1", List.of("2"));
graph.put("2", List.of("3"));
graph.put("3", List.of("4"));
graph.put("4", List.of("1"));
// Create the adjacency matrix from the graph
int[][] adjMatrix = createAdjacencyMatrix(graph);
// Print the adjacency matrix
for (int[] row : adjMatrix) {
for (int value : row) {
System.out.print(value + " ");
}
System.out.println();
}
}
}
// This code is contributed by shivamgupta0987654321
Python3
def create_adjacency_matrix(graph):
"""
Create an adjacency matrix for a directed graph.
Parameters:
graph (dict): A dictionary representing the directed graph.
Returns:
list: The adjacency matrix of the graph.
"""
vertices = sorted(graph.keys()) # Get sorted list of vertices
num_vertices = len(vertices)
# 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, vertex in enumerate(vertices):
for neighbor in graph[vertex]:
j = vertices.index(neighbor)
adj_matrix[i][j] = 1
return adj_matrix
# Example graph represented as a dictionary
# The keys are the vertices and the values are lists of neighboring vertices
graph = {
'1': ['2'],
'2': ['3'],
'3': ['4'],
'4': ['1']
}
# Create the adjacency matrix
adj_matrix = create_adjacency_matrix(graph)
# Print the adjacency matrix
for row in adj_matrix:
print(row)
JavaScript
function createAdjacencyMatrix(graph) {
const vertices = Object.keys(graph).sort();
const numVertices = vertices.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 (const neighbor of graph[vertices[i]]) {
const j = vertices.indexOf(neighbor);
adjMatrix[i][j] = 1;
}
}
return adjMatrix;
}
// Example graph represented as a dictionary
// The keys are the vertices and the values are lists of neighboring vertices
const graph = {
"1": ["2"],
"2": ["3"],
"3": ["4"],
"4": ["1"]
};
// Create the adjacency matrix
const adjMatrix = createAdjacencyMatrix(graph);
// Print the adjacency matrix
for (const row of adjMatrix) {
console.log(row.join(' '));
}
Output[0, 1, 0, 0]
[0, 0, 1, 0]
[0, 0, 0, 1]
[1, 0, 0, 0]
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Array Data Structure Guide In 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
4 min read