Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on Graph
  • Practice Graph
  • MCQs on Graph
  • Graph Tutorial
  • Graph Representation
  • Graph Properties
  • Types of Graphs
  • Graph Applications
  • BFS on Graph
  • DFS on Graph
  • Graph VS Tree
  • Transpose Graph
  • Dijkstra's Algorithm
  • Minimum Spanning Tree
  • Prim’s Algorithm
  • Topological Sorting
  • Floyd Warshall Algorithm
  • Strongly Connected Components
  • Advantages & Disadvantages
Open In App
Next Article:
Graph Adjacency Matrix in Java
Next article icon

Adjacency Matrix of Directed Graph

Last Updated : 29 Apr, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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:

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.

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.

Properties of Adjacency Matrix of Directed Graph:

  1. Diagonal Entries: The diagonal entries Aii​ are usually set to 0, assuming the graph has no self-loops.
  2. 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] 



Next Article
Graph Adjacency Matrix in Java

S

srinam
Improve
Article Tags :
  • Graph
  • DSA
Practice Tags :
  • Graph

Similar Reads

  • Print Adjacency List for a Directed Graph
    An Adjacency List is used for representing graphs. Here, for every vertex in the graph, we have a list of all the other vertices which the particular vertex has an edge to. Problem: Given the adjacency list and number of vertices and edges of a graph, the task is to represent the adjacency list for
    6 min read
  • Graph Adjacency Matrix in Java
    A graph is a type of data structure used to represent the relationship between the entities. In this article, we will learn to represent a graph in the form of Adjacency Matrix. Graph Adjacency MatrixThe Adjacency matrix is the way to represent the graphs using the 2D array. It is the fundamental da
    6 min read
  • Print adjacency list of a Bidirectional Graph
    Given the adjacency list of a bidirectional graph. The task is to copy/clone the adjacency list for each vertex and return a new list for a bidirectional graph. An Adjacency List is used for representing graphs. Here, for every vertex in the graph, we have a list of all the other vertices to which t
    7 min read
  • Adjacency Matrix in Python
    Given the edges of a graph as a list of tuples, construct an adjacency matrix to represent the graph in Python. Examples: Input:V = 3 (Number of vertices)edges = [(0, 1), (1, 2), (2, 0)] Output: [ [0, 1, 1], [1, 0, 1], [1, 1, 0]] Input:V = 4 (Number of vertices)edges = [(0, 1), (1, 2), (1, 3), (2, 3
    2 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 (wh
    8 min read
  • Detect Cycle in a Directed Graph
    Given the number of vertices V and a list of directed edges, determine whether the graph contains a cycle or not. Examples: Input: V = 4, edges[][] = [[0, 1], [0, 2], [1, 2], [2, 0], [2, 3]] Output: trueExplanation: The diagram clearly shows a cycle 0 → 2 → 0 Input: V = 4, edges[][] = [[0, 1], [0, 2
    15+ min read
  • Graph Representation using Adjacency Matrix in C
    A graph is a data structure having a set of vertices and a collection of edges that each connect a pair of vertices. There are several ways to represent a graph in computer memory, and one of them is using an adjacency matrix. An adjacency matrix is a 2D array with one row per vertex and one column
    4 min read
  • Shortest Path in Directed Acyclic Graph
    Given a Weighted Directed Acyclic Graph and a source vertex in the graph, find the shortest paths from given source to all other vertices. Recommended PracticeShortest path from 1 to nTry It! For a general weighted graph, we can calculate single source shortest distances in O(VE) time using Bellman–
    15 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
    7 min read
  • Longest Path in a Directed Acyclic Graph
    Given a Weighted Directed Acyclic Graph (DAG) and a source vertex s in it, find the longest distances from s to all other vertices in the given graph. The longest path problem for a general graph is not as easy as the shortest path problem because the longest path problem doesn’t have optimal substr
    15+ min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences