There are n nodes and there are edges between the nodes if they are connected directly. Each edge does not have weight and direction (If node a and b are connected, it means connected both way not one way).
Based on the graph, we can draw adjacency matrix which is two-dimensional array, A[0][0]...A[n-1][n-1]. So, the question is how to return the shortest path. If there is no path, should return empty path. And the path should return using linked list.
|A B C D E
A|0 1 0 1 0
B|1 0 1 0 0
C|0 1 0 1 0
D|1 0 1 0 1
E|0 0 0 1 0
So, based on the Matrix above, the shortest path from C to E is [C,D,E]. And the shortest path from A to C is [A,B,C].
We should use pseudo code with O(n^2) time complexity. And I briefly guess BFS approach would be great.
I believe this article answers your question. This problem can be solved with Dijkstra's algorithm. In your case the weight of each edge is equal to 1 so just make the dist_between(u,v) = 1
in the pseudo code. Time complexity of the solution is O(V^2). Note that, previous[v]
= the node previous to the vth node in the shortest path to node v from the starting node . That means, in order to visit the vth node in the shortest possible way, you have to first come to the previous [v]
node. So using this previous
array, you can return the shortest path in any way you desire. If there is no path, the dist[v]
in the pseudo code will be infinity.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.