1. Home
  2. Coding Hub
  3. Coding Notes
  4. Java
  5. Graph Adjacency Matrix
45% OFFBLACK FRIDAY SALE
Sale ends in
03Days
11Hrs
37Mins
09Secs
Claim
  1. Home
  2. Coding Hub
  3. Coding Notes
  4. Java
  5. Graph Adjacency Matrix

Limited time offer

45% OFF

BLACK FRIDAY SALE

Sale ends in

03Days
11Hrs
37Mins
09Secs
Claim
HTMLCSSJavaScriptPythonJavaC++React.jsSQLNext.jsNode.js
Underrated CoderUnderrated Coder
Underrated CoderUnderrated Coder
Resources
  • Coding Hub
  • Roadmap
  • DSA Sheet
  • Coding Notes
  • Coding Quiz
  • Code Compiler
  • Coder AI
Interview Preparation
  • 1:1 Mentorship
  • Interview Q&A
Community
  • Blog
  • Coder Community
Help & Support
  • Contact Us
  • Troubleshooting
  • Report a Bug
HTMLCSSJavaScriptPythonJavaC++React.jsSQLNext.jsNode.js
Outline
JVM ArchitectureVariablesData TypesOperatorsIf-Else StatementsSwitch StatementsLoops (For, While)Methods (Functions)Variable Scope1D Arrays2D ArraysStringsStringBuilder
Classes & ObjectsConstructorsThe this KeywordInheritanceThe super KeywordPolymorphismMethod OverloadingMethod OverridingEncapsulationAccess ModifiersAbstract ClassesInterfaces
Try-CatchThrow vs. ThrowsCustom ExceptionsArrayListHashMapHashSetWrapper ClassesAutoboxing & Unboxing
Lambda ExpressionsStreams APIThe Optional Class
Singly Linked ListDoubly Linked ListStackQueuePriority QueueHash Map InternalsCircular Linked ListMonotonic StackCircular Queue
Linear SearchBinary SearchTwo Pointers PatternBig O Space ComplexityInsertion SortMerge SortQuick SortFixed Sliding WindowVariable Sliding WindowPrefix Sum Pattern
Binary TreesBSTPrefix TreesMin-HeapMax-HeapGraph Adjacency ListGraph Adjacency Matrix
Recursion FundamentalsBacktrackingBreadth-First SearchLevel OrderTree DFSInorder TraversalPreorder TraversalPostorder TraversalGraph DFSDijkstra's AlgorithmTopological Sort1D Dynamic Programming2D Dynamic ProgrammingTop-Down (Memoization)Bottom-Up (Tabulation)Cycle DetectionMerge Intervals Pattern
Java

Graph Adjacency Matrix

Overview

An Adjacency Matrix is the second primary way to represent a graph. Instead of lists, it uses a 2D Array (a grid) of size V x V (Vertices by Vertices).

If there is an edge connecting Node 0 and Node 1, we set matrix[0][1] = 1. If there is no edge, it remains 0. For a weighted graph, we store the weight of the edge instead of a simple 1.

The massive advantage of a Matrix is O(1) edge lookup. If you want to know if Node 4 and Node 8 are connected, you simply check matrix[4][8].

However, the fatal flaw of the Matrix is Space Complexity. A graph with 10,000 vertices requires a 10,000 x 10,000 array, allocating 100 million integers (400MB of RAM)! Even if there are only 5 edges in the entire graph, it still uses 400MB. Therefore, Matrices are only used for Dense Graphs (where almost every node is connected to every other node) or very small graphs.

Syntax

Building an Adjacency Matrix
java
public class GraphMatrix {
    private int[][] matrix;
    private int numVertices;
    
    public GraphMatrix(int numVertices) {
        this.numVertices = numVertices;
        // In Java, integer arrays default to 0 (no edge)
        matrix = new int[numVertices][numVertices];
    }
    
    // Add an undirected edge
    public void addEdge(int i, int j) {
        matrix[i][j] = 1;
        matrix[j][i] = 1; // Undirected means mirrored across the diagonal
    }
    
    // Remove an edge
    public void removeEdge(int i, int j) {
        matrix[i][j] = 0;
        matrix[j][i] = 0;
    }
    
    // O(1) Check if connected
    public boolean isConnected(int i, int j) {
        return matrix[i][j] == 1;
    }
    
    // Print the matrix
    public void print() {
        for (int i = 0; i < numVertices; i++) {
            for (int j = 0; j < numVertices; j++) {
                System.out.print(matrix[i][j] + " ");
            }
            System.out.println();
        }
    }
}

Common Pitfalls

  • Running out of memory (OutOfMemoryError). Never use an Adjacency Matrix in a coding interview if the number of nodes N is greater than 1,000 unless specifically instructed to. $10^5$ nodes requires a $10^{10}$ size array, which will instantly crash your program.
  • Iterating over neighbors is extremely slow. To find all neighbors of Node 0, you must iterate through the entire row matrix[0], checking every single node from 1 to N to see if it equals 1. This makes traversal algorithms like BFS/DFS run in O(V^2) time instead of O(V + E).
  • Handling node IDs. A matrix requires node IDs to be sequential integers from 0 to V-1. If your nodes are Strings ('New York', 'London'), you must create an entirely separate HashMap<String, Integer> just to map the names to valid array indices.

Interview Questions

What is the time complexity to add an edge, remove an edge, and check if an edge exists in an Adjacency Matrix?

All three operations are strictly O(1) time complexity. You are just accessing and modifying a 2D array by index.

If a graph is Undirected, what visual property does its Adjacency Matrix have?

It is 'Symmetric' across its main diagonal. The value at matrix[i][j] will always exactly match the value at matrix[j][i].

Real-World Example

Flight routing maps between a small network of major airports. If you only have 50 major airports, a 50x50 matrix is tiny. A matrix perfectly models a dense network where almost every airport has direct flights to every other airport. The matrix cells can hold the flight cost or distance (Weighted Graph).

example
java
// A weighted adjacency matrix
int numAirports = 5;
int[][] flightCosts = new int[numAirports][numAirports];

// Initialize all routes to 'Infinity' (No route exists)
for(int[] row : flightCosts) {
    Arrays.fill(row, Integer.MAX_VALUE);
}

// JFK (0) to LAX (1) costs $450
flightCosts[0][1] = 450;
flightCosts[1][0] = 450;

Check Your Knowledge

Test your understanding of Graph Adjacency Matrix with these quick questions.

Question 1

What is the space complexity of an Adjacency Matrix for a graph with V vertices?

Question 2

When is an Adjacency Matrix the superior choice over an Adjacency List?

Question 3

How do you represent a 'Weighted Graph' using an Adjacency Matrix?

Take Java Quiz
Outline
JVM ArchitectureVariablesData TypesOperatorsIf-Else StatementsSwitch StatementsLoops (For, While)Methods (Functions)Variable Scope1D Arrays2D ArraysStringsStringBuilder
Classes & ObjectsConstructorsThe this KeywordInheritanceThe super KeywordPolymorphismMethod OverloadingMethod OverridingEncapsulationAccess ModifiersAbstract ClassesInterfaces
Try-CatchThrow vs. ThrowsCustom ExceptionsArrayListHashMapHashSetWrapper ClassesAutoboxing & Unboxing
Lambda ExpressionsStreams APIThe Optional Class
Singly Linked ListDoubly Linked ListStackQueuePriority QueueHash Map InternalsCircular Linked ListMonotonic StackCircular Queue
Linear SearchBinary SearchTwo Pointers PatternBig O Space ComplexityInsertion SortMerge SortQuick SortFixed Sliding WindowVariable Sliding WindowPrefix Sum Pattern
Binary TreesBSTPrefix TreesMin-HeapMax-HeapGraph Adjacency ListGraph Adjacency Matrix
Recursion FundamentalsBacktrackingBreadth-First SearchLevel OrderTree DFSInorder TraversalPreorder TraversalPostorder TraversalGraph DFSDijkstra's AlgorithmTopological Sort1D Dynamic Programming2D Dynamic ProgrammingTop-Down (Memoization)Bottom-Up (Tabulation)Cycle DetectionMerge Intervals Pattern
Java

Graph Adjacency Matrix

Overview

An Adjacency Matrix is the second primary way to represent a graph. Instead of lists, it uses a 2D Array (a grid) of size V x V (Vertices by Vertices).

If there is an edge connecting Node 0 and Node 1, we set matrix[0][1] = 1. If there is no edge, it remains 0. For a weighted graph, we store the weight of the edge instead of a simple 1.

The massive advantage of a Matrix is O(1) edge lookup. If you want to know if Node 4 and Node 8 are connected, you simply check matrix[4][8].

However, the fatal flaw of the Matrix is Space Complexity. A graph with 10,000 vertices requires a 10,000 x 10,000 array, allocating 100 million integers (400MB of RAM)! Even if there are only 5 edges in the entire graph, it still uses 400MB. Therefore, Matrices are only used for Dense Graphs (where almost every node is connected to every other node) or very small graphs.

Syntax

Building an Adjacency Matrix
java
public class GraphMatrix {
    private int[][] matrix;
    private int numVertices;
    
    public GraphMatrix(int numVertices) {
        this.numVertices = numVertices;
        // In Java, integer arrays default to 0 (no edge)
        matrix = new int[numVertices][numVertices];
    }
    
    // Add an undirected edge
    public void addEdge(int i, int j) {
        matrix[i][j] = 1;
        matrix[j][i] = 1; // Undirected means mirrored across the diagonal
    }
    
    // Remove an edge
    public void removeEdge(int i, int j) {
        matrix[i][j] = 0;
        matrix[j][i] = 0;
    }
    
    // O(1) Check if connected
    public boolean isConnected(int i, int j) {
        return matrix[i][j] == 1;
    }
    
    // Print the matrix
    public void print() {
        for (int i = 0; i < numVertices; i++) {
            for (int j = 0; j < numVertices; j++) {
                System.out.print(matrix[i][j] + " ");
            }
            System.out.println();
        }
    }
}

Common Pitfalls

  • Running out of memory (OutOfMemoryError). Never use an Adjacency Matrix in a coding interview if the number of nodes N is greater than 1,000 unless specifically instructed to. $10^5$ nodes requires a $10^{10}$ size array, which will instantly crash your program.
  • Iterating over neighbors is extremely slow. To find all neighbors of Node 0, you must iterate through the entire row matrix[0], checking every single node from 1 to N to see if it equals 1. This makes traversal algorithms like BFS/DFS run in O(V^2) time instead of O(V + E).
  • Handling node IDs. A matrix requires node IDs to be sequential integers from 0 to V-1. If your nodes are Strings ('New York', 'London'), you must create an entirely separate HashMap<String, Integer> just to map the names to valid array indices.

Interview Questions

What is the time complexity to add an edge, remove an edge, and check if an edge exists in an Adjacency Matrix?

All three operations are strictly O(1) time complexity. You are just accessing and modifying a 2D array by index.

If a graph is Undirected, what visual property does its Adjacency Matrix have?

It is 'Symmetric' across its main diagonal. The value at matrix[i][j] will always exactly match the value at matrix[j][i].

Real-World Example

Flight routing maps between a small network of major airports. If you only have 50 major airports, a 50x50 matrix is tiny. A matrix perfectly models a dense network where almost every airport has direct flights to every other airport. The matrix cells can hold the flight cost or distance (Weighted Graph).

example
java
// A weighted adjacency matrix
int numAirports = 5;
int[][] flightCosts = new int[numAirports][numAirports];

// Initialize all routes to 'Infinity' (No route exists)
for(int[] row : flightCosts) {
    Arrays.fill(row, Integer.MAX_VALUE);
}

// JFK (0) to LAX (1) costs $450
flightCosts[0][1] = 450;
flightCosts[1][0] = 450;

Check Your Knowledge

Test your understanding of Graph Adjacency Matrix with these quick questions.

Question 1

What is the space complexity of an Adjacency Matrix for a graph with V vertices?

Question 2

When is an Adjacency Matrix the superior choice over an Adjacency List?

Question 3

How do you represent a 'Weighted Graph' using an Adjacency Matrix?

Take Java Quiz

Java coding notes for Indian students — 79 topics with syntax, pitfalls, interview Q&A, and inline quizzes.

Topics in Java

  1. JVM Architecture
  2. Variables
  3. Data Types
  4. Operators
  5. If-Else Statements
  6. Switch Statements
  7. Loops (For, While)
  8. Methods (Functions)
  9. Variable Scope
  10. 1D Arrays
  11. 2D Arrays
  12. Strings
  13. StringBuilder
  14. Classes & Objects
  15. Constructors
  16. The this Keyword
  17. Inheritance
  18. The super Keyword
  19. Polymorphism
  20. Method Overloading
  21. Method Overriding
  22. Encapsulation
  23. Access Modifiers
  24. Abstract Classes
  25. Interfaces
  26. Try-Catch
  27. Throw vs. Throws
  28. Custom Exceptions
  29. ArrayList
  30. HashMap
  31. HashSet
  32. Wrapper Classes
  33. Autoboxing & Unboxing
  34. Lambda Expressions
  35. Streams API
  36. The Optional Class
  37. Singly Linked List
  38. Doubly Linked List
  39. Stack
  40. Queue
  41. Priority Queue
  42. Hash Map Internals
  43. Circular Linked List
  44. Monotonic Stack
  45. Circular Queue
  46. Linear Search
  47. Binary Search
  48. Two Pointers Pattern
  49. Big O Space Complexity
  50. Insertion Sort
  51. Merge Sort
  52. Quick Sort
  53. Fixed Sliding Window
  54. Variable Sliding Window
  55. Prefix Sum Pattern
  56. Binary Trees
  57. BST
  58. Prefix Trees
  59. Min-Heap
  60. Max-Heap
  61. Graph Adjacency List
  62. Graph Adjacency Matrix
  63. Recursion Fundamentals
  64. Backtracking
  65. Breadth-First Search
  66. Level Order
  67. Tree DFS
  68. Inorder Traversal
  69. Preorder Traversal
  70. Postorder Traversal
  71. Graph DFS
  72. Dijkstra's Algorithm
  73. Topological Sort
  74. 1D Dynamic Programming
  75. 2D Dynamic Programming
  76. Top-Down (Memoization)
  77. Bottom-Up (Tabulation)
  78. Cycle Detection
  79. Merge Intervals Pattern

Study next

  • All coding notes
  • Java notes home
  • Java certification quiz
  • Online compiler
  • Interview Q&A

Java coding notes for Indian students — 79 topics with syntax, pitfalls, interview Q&A, and inline quizzes.

Topics in Java

  1. JVM Architecture
  2. Variables
  3. Data Types
  4. Operators
  5. If-Else Statements
  6. Switch Statements
  7. Loops (For, While)
  8. Methods (Functions)
  9. Variable Scope
  10. 1D Arrays
  11. 2D Arrays
  12. Strings
  13. StringBuilder
  14. Classes & Objects
  15. Constructors
  16. The this Keyword
  17. Inheritance
  18. The super Keyword
  19. Polymorphism
  20. Method Overloading
  21. Method Overriding
  22. Encapsulation
  23. Access Modifiers
  24. Abstract Classes
  25. Interfaces
  26. Try-Catch
  27. Throw vs. Throws
  28. Custom Exceptions
  29. ArrayList
  30. HashMap
  31. HashSet
  32. Wrapper Classes
  33. Autoboxing & Unboxing
  34. Lambda Expressions
  35. Streams API
  36. The Optional Class
  37. Singly Linked List
  38. Doubly Linked List
  39. Stack
  40. Queue
  41. Priority Queue
  42. Hash Map Internals
  43. Circular Linked List
  44. Monotonic Stack
  45. Circular Queue
  46. Linear Search
  47. Binary Search
  48. Two Pointers Pattern
  49. Big O Space Complexity
  50. Insertion Sort
  51. Merge Sort
  52. Quick Sort
  53. Fixed Sliding Window
  54. Variable Sliding Window
  55. Prefix Sum Pattern
  56. Binary Trees
  57. BST
  58. Prefix Trees
  59. Min-Heap
  60. Max-Heap
  61. Graph Adjacency List
  62. Graph Adjacency Matrix
  63. Recursion Fundamentals
  64. Backtracking
  65. Breadth-First Search
  66. Level Order
  67. Tree DFS
  68. Inorder Traversal
  69. Preorder Traversal
  70. Postorder Traversal
  71. Graph DFS
  72. Dijkstra's Algorithm
  73. Topological Sort
  74. 1D Dynamic Programming
  75. 2D Dynamic Programming
  76. Top-Down (Memoization)
  77. Bottom-Up (Tabulation)
  78. Cycle Detection
  79. Merge Intervals Pattern

Study next

  • All coding notes
  • Java notes home
  • Java certification quiz
  • Online compiler
  • Interview Q&A