# Java Program to Implement Johnson’s Algorithm

«
»
This Java program is to Implement Johnson’s algorithm. Johnson’s algorithm is a way to find the shortest paths between all pairs of vertices in a sparse, edge weighted, directed graph. It allows some of the edge weights to be negative numbers, but no negative-weight cycles may exist. It works by using the Bellman–Ford algorithm to compute a transformation of the input graph that removes all negative weights, allowing Dijkstra’s algorithm to be used on the transformed graph.

Here is the source code of the Java program to implement Johnson algorithm. The Java program is successfully compiled and run on a Linux system. The program output is also shown below.

1. `import java.util.InputMismatchException;`
2. `import java.util.Scanner;`
3. `public class JohnsonsAlgorithm `
4. `{`
5. `    private int SOURCE_NODE;`
6. `    private int numberOfNodes;`
7. `    private int augmentedMatrix[][];`
8. `    private int potential[];`
9. `    private BellmanFord bellmanFord;`
10. `    private DijkstraShortesPath dijsktraShortesPath;`
11. `    private int[][] allPairShortestPath;`
12. ` `
13. `    public static final int MAX_VALUE = 999;`
14. ` `
15. `    public JohnsonsAlgorithm(int numberOfNodes)`
16. `    {`
17. `        this.numberOfNodes = numberOfNodes;`
18. `        augmentedMatrix = new int[numberOfNodes + 2][numberOfNodes + 2];`
19. `        SOURCE_NODE = numberOfNodes + 1;`
20. `        potential = new int[numberOfNodes + 2];`
21. `        bellmanFord = new BellmanFord(numberOfNodes + 1);`
22. `        dijsktraShortesPath = new DijkstraShortesPath(numberOfNodes);`
23. `        allPairShortestPath = new int[numberOfNodes + 1][numberOfNodes + 1];`
24. `    }`
25. ` `
26. `    public void johnsonsAlgorithms(int adjacencyMatrix[][])`
27. `    {`
28. `        computeAugmentedGraph(adjacencyMatrix);`
29. ` `
30. `        bellmanFord.BellmanFordEvaluation(SOURCE_NODE, augmentedMatrix);`
31. `        potential = bellmanFord.getDistances();`
32. ` `
33. `        int reweightedGraph[][] = reweightGraph(adjacencyMatrix);`
34. `        for (int i = 1; i <= numberOfNodes; i++)`
35. `        {`
36. `            for (int j = 1; j <= numberOfNodes; j++)`
37. `            {`
38. `                System.out.print(reweightedGraph[i][j] + "\t");`
39. `            }`
40. `            System.out.println();`
41. `        }`
42. ` `
43. `        for (int source = 1; source <= numberOfNodes; source++)`
44. `        {`
45. `            dijsktraShortesPath.dijkstraShortestPath(source, reweightedGraph);`
46. `            int[] result = dijsktraShortesPath.getDistances();`
47. `            for (int destination = 1; destination <= numberOfNodes; destination++)`
48. `            {`
49. `                allPairShortestPath[source][destination] = result[destination] `
50. `                        + potential[destination] - potential[source];`
51. `            }`
52. `        }`
53. ` `
54. `        System.out.println();`
55. `        for (int i = 1; i<= numberOfNodes; i++)`
56. `        {`
57. `            System.out.print("\t"+i);`
58. `        }`
59. `        System.out.println();`
60. `        for (int source = 1; source <= numberOfNodes; source++)`
61. `        {`
62. `            System.out.print( source +"\t" );`
63. `            for (int destination = 1; destination <= numberOfNodes; destination++)`
64. `            {`
65. `                System.out.print(allPairShortestPath[source][destination]+ "\t");`
66. `            }`
67. `            System.out.println();`
68. `        }`
69. `    }`
70. ` `
71. `    private void computeAugmentedGraph(int adjacencyMatrix[][])`
72. `    {`
73. `        for (int source = 1; source <= numberOfNodes; source++)`
74. `        {`
75. `            for (int destination = 1; destination <= numberOfNodes; destination++)`
76. `            { `
77. `                augmentedMatrix[source][destination] = adjacencyMatrix[source][destination];`
78. `            }`
79. `        }`
80. `        for (int destination = 1; destination <= numberOfNodes; destination++)`
81. `        {`
82. `            augmentedMatrix[SOURCE_NODE][destination] = 0;`
83. `        }`
84. `    }`
85. ` `
86. `    private int[][] reweightGraph(int adjacencyMatrix[][])`
87. `    {`
88. `        int[][] result = new int[numberOfNodes + 1][numberOfNodes + 1];`
89. `        for (int source = 1; source <= numberOfNodes; source++)`
90. `        {`
91. `            for (int destination = 1; destination <= numberOfNodes; destination++)`
92. `            {`
93. `                result[source][destination] = adjacencyMatrix[source][destination]`
94. `                       + potential[source] - potential[destination];`
95. `            }`
96. `        }`
97. `        return result;`
98. `    }`
99. ` `
100. `    public static void main(String... arg)`
101. `    {`
102. `        int adjacency_matrix[][];`
103. `        int number_of_vertices;`
104. `        Scanner scan = new Scanner(System.in);`
105. ` `
106. `        try`
107. `        {`
108. `            System.out.println("Enter the number of vertices");`
109. `            number_of_vertices = scan.nextInt();`
110. `            adjacency_matrix = new int[number_of_vertices + 1][number_of_vertices + 1];`
111. ` `
112. `            System.out.println("Enter the Weighted Matrix for the graph");`
113. `            for (int i = 1; i <= number_of_vertices; i++)`
114. `            {`
115. `                for (int j = 1; j <= number_of_vertices; j++)`
116. `                {`
117. `                    adjacency_matrix[i][j] = scan.nextInt();`
118. `                    if (i == j) `
119. `                    {`
120. `                        adjacency_matrix[i][j] = 0;`
121. `                        continue;`
122. `                    }`
123. `                    if (adjacency_matrix[i][j] == 0)`
124. `                    {`
125. `                        adjacency_matrix[i][j] = MAX_VALUE;`
126. `                    }`
127. `                }`
128. `            }`
129. ` `
130. `            JohnsonsAlgorithm johnsonsAlgorithm = new JohnsonsAlgorithm(number_of_vertices);`
131. `            johnsonsAlgorithm.johnsonsAlgorithms(adjacency_matrix);`
132. `        } catch (InputMismatchException inputMismatch)`
133. `        {`
134. `            System.out.println("Wrong Input Format");`
135. `        }`
136. `        scan.close();`
137. `    }`
138. `}`
139. ` `
140. `class BellmanFord `
141. `{`
142. `    private int distances[];`
143. `    private int numberofvertices;`
144. ` `
145. `    public static final int MAX_VALUE = 999;`
146. ` `
147. `    public BellmanFord(int numberofvertices)  `
148. `    {`
149. `        this.numberofvertices = numberofvertices;`
150. `        distances = new int[numberofvertices + 1];`
151. `    }`
152. ` `
153. `    public void BellmanFordEvaluation(int source, int adjacencymatrix[][])`
154. `    {`
155. `        for (int node = 1; node <= numberofvertices; node++)`
156. `        {`
157. `            distances[node] = MAX_VALUE;`
158. `        }`
159. ` `
160. `        distances[source] = 0;`
161. ` `
162. `        for (int node = 1; node <= numberofvertices - 1; node++)`
163. `        {`
164. `            for (int sourcenode = 1; sourcenode <= numberofvertices; sourcenode++)`
165. `            {`
166. `                for (int destinationnode = 1; destinationnode <= numberofvertices; destinationnode++)`
167. `                {`
168. `                    if (adjacencymatrix[sourcenode][destinationnode] != MAX_VALUE)`
169. `                    {`
170. `                        if (distances[destinationnode] > distances[sourcenode] `
171. `                               + adjacencymatrix[sourcenode][destinationnode])`
172. `                        {`
173. `                            distances[destinationnode] = distances[sourcenode]`
174. `                               + adjacencymatrix[sourcenode][destinationnode];`
175. `                        }`
176. `                    }`
177. `                }`
178. `            }`
179. `        }`
180. ` `
181. `        for (int sourcenode = 1; sourcenode <= numberofvertices; sourcenode++)`
182. `        {`
183. `            for (int destinationnode = 1; destinationnode <= numberofvertices; destinationnode++)`
184. `            {`
185. `                if (adjacencymatrix[sourcenode][destinationnode] != MAX_VALUE)`
186. `                {`
187. `                    if (distances[destinationnode] > distances[sourcenode]`
188. `                            + adjacencymatrix[sourcenode][destinationnode])`
189. `                        System.out.println("The Graph contains negative egde cycle");`
190. `	        }`
191. `            }`
192. `        }`
193. `    }`
194. ` `
195. `    public int[] getDistances()`
196. `    {`
197. `        return distances;`
198. `    }`
199. `}`
200. ` `
201. `class DijkstraShortesPath`
202. `{`
203. `    private boolean settled[];`
204. `    private boolean unsettled[];`
205. `    private int distances[];`
206. `    private int adjacencymatrix[][];`
207. `    private int numberofvertices;`
208. ` `
209. `    public static final int MAX_VALUE = 999;`
210. ` `
211. `    public DijkstraShortesPath(int numberofvertices)`
212. `    {`
213. `        this.numberofvertices = numberofvertices;`
214. `    }`
215. ` `
216. `    public void dijkstraShortestPath(int source, int adjacencymatrix[][])`
217. `    {`
218. `        this.settled = new boolean[numberofvertices + 1];`
219. `        this.unsettled = new boolean[numberofvertices + 1];`
220. `        this.distances = new int[numberofvertices + 1];`
221. `        this.adjacencymatrix = new int[numberofvertices + 1][numberofvertices + 1];`
222. ` `
223. `        int evaluationnode;`
224. `        for (int vertex = 1; vertex <= numberofvertices; vertex++)`
225. `        {`
226. `            distances[vertex] = MAX_VALUE;`
227. `        }`
228. ` `
229. `        for (int sourcevertex = 1; sourcevertex <= numberofvertices; sourcevertex++)`
230. `        {`
231. `            for (int destinationvertex = 1; destinationvertex <= numberofvertices; destinationvertex++)`
232. `            {`
233. `                this.adjacencymatrix[sourcevertex][destinationvertex] `
234. `                     = adjacencymatrix[sourcevertex][destinationvertex];`
235. `            }`
236. `        }`
237. ` `
238. `        unsettled[source] = true;`
239. `        distances[source] = 0;`
240. `        while (getUnsettledCount(unsettled) != 0)`
241. `        {`
242. `            evaluationnode = getNodeWithMinimumDistanceFromUnsettled(unsettled);`
243. `            unsettled[evaluationnode] = false;`
244. `            settled[evaluationnode] = true;`
245. `            evaluateNeighbours(evaluationnode);`
246. `        }`
247. `    } `
248. ` `
249. `    public int getUnsettledCount(boolean unsettled[])`
250. `    {`
251. `        int count = 0;`
252. `        for (int vertex = 1; vertex <= numberofvertices; vertex++)`
253. `        {`
254. `            if (unsettled[vertex] == true)`
255. `            {`
256. `                count++;`
257. `            }`
258. `        }`
259. `        return count;`
260. `    }`
261. ` `
262. `    public int getNodeWithMinimumDistanceFromUnsettled(boolean unsettled[])`
263. `    {`
264. `        int min = MAX_VALUE;`
265. `        int node = 0;`
266. `        for (int vertex = 1; vertex <= numberofvertices; vertex++)`
267. `        {`
268. `            if (unsettled[vertex] == true && distances[vertex] < min)`
269. `            {`
270. `                node = vertex;`
271. `                min = distances[vertex];`
272. `            }`
273. `        }`
274. `        return node;`
275. `    }`
276. ` `
277. `    public void evaluateNeighbours(int evaluationNode)`
278. `    {`
279. `        int edgeDistance = -1;`
280. `        int newDistance = -1;`
281. ` `
282. `        for (int destinationNode = 1; destinationNode <= numberofvertices; destinationNode++)`
283. `        {`
284. `            if (settled[destinationNode] == false)`
285. `            {`
286. `                if (adjacencymatrix[evaluationNode][destinationNode] != MAX_VALUE)`
287. `                {`
288. `                    edgeDistance = adjacencymatrix[evaluationNode][destinationNode];`
289. `                    newDistance = distances[evaluationNode] + edgeDistance;`
290. `                    if (newDistance < distances[destinationNode])`
291. `                    {`
292. `                        distances[destinationNode] = newDistance;`
293. `                    }`
294. `                    unsettled[destinationNode] = true;`
295. `                }`
296. `            }`
297. `        }`
298. `    }`
299. ` `
300. `    public int[] getDistances()`
301. `    {`
302. `        return distances;`
303. `    }`
304. `}`

```\$javac JohnsonsAlgorithm .java
\$java JohnsonsAlgorithm
Enter the number of vertices
4
Enter the Weighted Matrix for the graph
0 0 3 0
2 0 0 0
0 7 0 1
6 0 0 0

All pair shortest path is
1	2	3	4
1	0	10	3	4
2	2	0	5	6
3	7	7	0	1
4	6	16	9	0```

Sanfoundry Global Education & Learning Series – 1000 Java Programs.

Sanfoundry Certification Contest of the Month is Live. 100+ Subjects. Participate Now!