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