Learnitweb

Adjacency matrix and adjacency list implementation

1. Introduction

In this tutorial, we’ll see the implementation of adjacency list and adjacency matrix representation of graph.

2. Adjacency Matrix Implementation

Consider the following two dimensional array representing an adjacency matrix representing a graph. The program finds all the edges in the graph.

public class AdjacencyMatrix {
    private static int[][] adjacencyMatrix = {
            {0,5,4,0},
            {0,0,0,3},
            {0,0,0,0},
            {0,0,0,0}
    };

    public static void main(String[] args){
        //find and print all edges
        for(int i=0; i<adjacencyMatrix.length; i++){
            for(int j=0; j<adjacencyMatrix.length; j++){
                if(adjacencyMatrix[i][j] != 0){
                    System.out.println("Edge with weight: " + adjacencyMatrix[i][j]);
                }
            }
        }
    }
}

Output

Edge with weight: 5
Edge with weight: 4
Edge with weight: 3

3. Adjacency list representation

For the Adjacency List Representation, we’ll first define a vertex or node. The Vertex class represents vertex or node in a graph. The Vertex has methods to declare the neighbors. There are no other special methods in this class.

Vertex.java

public class Vertex {
    private String name;
    private List<Vertex> adjacencyList;

    public Vertex(String name){
        this.name = name;
        this.adjacencyList = new ArrayList<>();
    }

    // Method to add neighbor to the current vertex
    public void addNeighbor(Vertex vertex){
        adjacencyList.add(vertex);
    }

    // Method to get neighbors of the matrix
    public void showNeighbors(){
        for(Vertex v: adjacencyList){
            System.out.println(v);
        }
    }

    @Override
    public String toString(){
        return name;
    }
}

AdjacencyListExample.java

public class AdjacencyListExample {
    public static void main(String args[]){
        Vertex a = new Vertex("A");
        Vertex b = new Vertex("B");
        Vertex c = new Vertex("C");
        Vertex d = new Vertex("D");

        a.addNeighbor(b);
        a.addNeighbor(c);
        b.addNeighbor(d);
        
        //print neighbors
        System.out.println("Neighbor of A: ");
        a.showNeighbors();
        System.out.println("Neighbor of B: ");
        b.showNeighbors();
        System.out.println("Neighbor of C: ");
        c.showNeighbors();
        System.out.println("Neighbor of D: ");
        d.showNeighbors();
    }
}

Output

Neighbor of A: 
B
C
Neighbor of B: 
D
Neighbor of C: 
Neighbor of D: 

4. Conclusion

In this short tutorial, we have a simple implementation of Adjacency List and Adjacency matrix representation of a graph.