Check out the Pastebin Gadgets Shop. We have thousands of fun, geeky & affordable gadgets on sale :-)Want more features on Pastebin? Sign Up, it's FREE!

# Dijkstra's - Stack overflow answer.

By: a guest on May 2nd, 2012  |  syntax: Java  |  size: 1.49 KB  |  views: 183  |  expires: Never
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
1. I think I may have solved the issue, by modifying the code as follows (I'm now passing in a start point instead of the hard-coded in "0"):
2.
3.        private static int dijkstras(Graph g, int start) // Added a start point.
4.        {
5.        // Dijkstra's Algorithm
6.         int[] best = new int[g.network.length];
7.         boolean[] visited = new boolean[g.network.length];
8.         int max = 10000; // Infinity equivalent.
9.         for (int i = 0; i < g.network.length; i++)
10.         {
11.             best[i] = max;
12.             visited[i] = false;
13.         }
14.
15.         best[start] = start; // Changed the 0 to variable start.
16.
17.         for(int i = 0; i < g.network.length; i++)
18.         {
19.             int min = max;
20.             int currentNode = 0;
21.             for (int j = 0; j < g.network.length; j++)
22.             {
23.                 if (!visited[j] && best[j] < min)
24.                 {
25.                     currentNode = j;
26.                     min = best[j];
27.                 }
28.             }
29.             visited[currentNode] = true;
30.             for (int j = 0; j < g.network.length; j++)
31.             {
32.                 if (g.network[currentNode][j] < max && best[currentNode] +   g.network[currentNode][j] < best[j])
33.                 {
34.                     best[j] = best[currentNode] + g.network[currentNode][j];
35.                 }
36.             }
37.         }
38.                 return best[g.network.length - 2];
39.     }
40.
41. I ran this code through a for loop and voila....not just zero's being returned now.
clone this paste RAW Paste Data
Top