If you do graph, sooner or later you will reach this point, Dijkstra :)
This Dutch computer scientist is/was more famous for his surprising quotes, and his huge amount of reading, while here we just quote his algorithm of shortest path in a directed and cyclic graph.
In the upper graph, what's the shortest path (distance) from vertex 1 to each vertex?
1->1 : 0 for sure;
1->2: 4? nope, 3 is correct;
1->3: 2 for sure;
1->4:
1->5:
1->6: unreachable, marked with -1 would be ok.
so, here is my java solution to shortest path problems like this one:
https://github.com/breezedu/rosalind/blob/master/DijkstraAlgorithm.java
the readin txt document and output result document are also available:
https://github.com/breezedu/rosalind/blob/master/TXT/dijk.txt
and
https://github.com/breezedu/rosalind/blob/master/TXT/dijk_output.txt
There are too many lectures online, but very few available questions/solutions with solid codes, so, feel free to check my codes.
in my codes, I did not use typical graph API, instead I used an arraylist to store all neighbor vertices of each vertex;
then I built a matrix to store distance between two vertices, like the distance from v1 to v2 is distMatrix[v1][v2].
Create an array to mark whether vertex[n] have been visited or not: (vert[] array);
Create an array to indicate the potential shortest distance from initial vertex to each vertex, dist[] array, dist[1] = 0;
call dijkstra() method to recursively calculate the distance from initial vertex to each vertex.
by the end of dijkstra() method, mark current vertex as visited (change vert[i] = 0 to vert[i] = 1);
check out the minimum distance from these un-visited vertices; set that vertex as the current vertex, call dijkstra() to calculate the newly assigned current vertex;
:)