File tree Expand file tree Collapse file tree 1 file changed +55
-0
lines changed
src/main/java/com/packt/datastructuresandalg/lesson6/graph Expand file tree Collapse file tree 1 file changed +55
-0
lines changed Original file line number Diff line number Diff line change 1+ package com .packt .datastructuresandalg .lesson6 .graph ;
2+
3+ import java .util .ArrayList ;
4+
5+ public class AdjacencyListWeightedGraph {
6+ private class Edge {
7+ int u , v , weight ;
8+
9+ public Edge (int u , int v , int weight ) {
10+ this .u = u ;
11+ this .v = v ;
12+ this .weight = weight ;
13+ }
14+ }
15+
16+ ArrayList <Edge >[] adj ;
17+
18+ public AdjacencyListWeightedGraph (int nodes ) {
19+ this .adj = new ArrayList [nodes ];
20+ for (int i = 0 ; i < nodes ; i ++)
21+ this .adj [i ] = new ArrayList <>();
22+ }
23+
24+ public void addEdge (int u , int v , int weight ) {
25+ this .adj [u ].add (new Edge (u , v , weight ));
26+ }
27+
28+ @ Override
29+ public String toString () {
30+ String res = "" ;
31+ for (int i = 0 ; i < adj .length ; i ++) {
32+ res += (i + ":" );
33+ for (int j = 0 ; j < adj [i ].size (); j ++) {
34+ Edge edge = adj [i ].get (j );
35+ res += (" " + edge .v + "(" + edge .weight + ")" );
36+ }
37+ if (i + 1 < adj .length )
38+ res += "\n " ;
39+ }
40+ return res ;
41+ }
42+
43+ public static void main (String [] args ) {
44+ AdjacencyListWeightedGraph g = new AdjacencyListWeightedGraph (6 );
45+ g .addEdge (0 , 1 , 1 );
46+ g .addEdge (0 , 3 , 4 );
47+ g .addEdge (1 , 4 , 3 );
48+ g .addEdge (2 , 4 , 10 );
49+ g .addEdge (2 , 5 , 4 );
50+ g .addEdge (3 , 1 , 5 );
51+ g .addEdge (4 , 3 , 1 );
52+ g .addEdge (5 , 5 , 2 );
53+ System .out .println (g );
54+ }
55+ }
You can’t perform that action at this time.
0 commit comments