This post will cover graph implementation in Java using Collections for weighted and unweighted, graph, and digraph.

We know that in an adjacency list representation of the graph, each vertex in the graph is associated with its neighboring vertices or edges. In other words, every vertex stores a list of adjacent vertices.

Directed Graph

For example, below is the pictorial representation for the corresponding adjacency list for the above graph:

 
Adjacency List

1. Directed Graph (Digraph) Implementation

Following is the Java implementation of a digraph using an adjacency list:

Download  Run Code

Output:

(0 ——> 1)
(1 ——> 2)
(2 ——> 0)    (2 ——> 1)
(3 ——> 2)
(4 ——> 5)
(5 ——> 4)

 
As evident from the above code, an edge is created from src to dest in the adjacency list in a digraph, and if the graph is undirected, additionally construct an edge from dest to src in the adjacency list.

2. Weighted Digraph Implementation

We know that in a weighted graph, every edge will have a weight or cost associated with it, as shown below:

Weighted Digraph

Following is the Java implementation of a weighted digraph using an adjacency list. The implementation is similar to that of an unweighted digraph, except storing the weight information in an adjacency list with every edge.

Download  Run Code

Output:

0 ——> 1 (6)
1 ——> 2 (7)
2 ——> 0 (5)    2 ——> 1 (4)
3 ——> 2 (10)
4 ——> 5 (1)
5 ——> 4 (3)

 
Also see:

Implement Graph Data Structure in C

Graph Implementation in C++ using STL

Graph Implementation in Python