现在我们在 O(1) 时间内从数组 d 中获得从源顶点source到任何其他顶点的路径长度,并且为了打印从源到任何顶点的路径,我们可以使用数组 p 并且在最坏的情况下将花费 O(V) 时间,因为 V 是数组 P 的大小。所以算法的大部分时间都花在从给定的源顶点source进行广度优先搜索上,我们知道这需要 O(V+E) 时间。因此我们算法的时间复杂度是 O(V+E)
Code:
importjava.util.*;publicclassShortestPath{staticclass _1st {}privatestaticvoidaddEdge(List<List<Integer>> adj,int u,int v){
adj.get(u).add(v);
adj.get(v).add(u);}/**
* @param adj 邻接表
* @param src 源点
* @param dest 终点
* @param V 顶点的个数
*/publicstaticvoidprintShortestDistance(List<List<Integer>> adj,int src,int dest,intV){int[] dist =newint[V];int[] pred =newint[V];if(!bfs(adj, src, dest,V, pred, dist)){System.out.println("Given source and destination are not connected");return;}List<Integer> path =newArrayList<>();int cur = dest;
path.add(cur);while(pred[cur]!=-1){
path.add(pred[cur]);
cur = pred[cur];}// Print distanceSystem.out.println("Shortest path length is: "+ dist[dest]);// Print pathSystem.out.println("Path is ::");for(int i = path.size()-1; i >=0; i--){System.out.print(path.get(i)+" ");}}privatestaticbooleanbfs(List<List<Integer>> adj,int src,int dest,intV,int[] pred,int[] dist){//存顶点的邻接点将要被访问的Queue<Integer> queue =newLinkedList<>();//记录当前节点至少被访问过一次boolean[] vis =newboolean[V];//初始化dist 和 pred 初始距离为MAX 直接前驱节点初始化为-1 不存在的节点Arrays.fill(dist,Integer.MAX_VALUE);Arrays.fill(pred,-1);//src点作为起始点开始转bfs遍历
vis[src]=true;
dist[src]=0;
queue.offer(src);while(!queue.isEmpty()){int u = queue.poll();for(int v : adj.get(u)){if(!vis[v]){//u相邻的节点v,v没有被访问过
vis[v]=true;
dist[v]= dist[u]+1;
pred[v]= u;
queue.offer(v);//当前的节点v的直接前驱节点修改为uif(v == dest)returntrue;//找到了}}}returnfalse;}publicstaticvoidmain(String args[]){// No of verticesintV=8;// Adjacency list for storing which vertices are connectedList<List<Integer>> adj =newArrayList<>();for(int i =0; i <V; i++){
adj.add(newArrayList<>());}// Creating graph given in the above diagram.// add_edge function takes adjacency list, source// and destination vertex as argument and forms// an edge between them.addEdge(adj,0,1);addEdge(adj,0,3);addEdge(adj,1,2);addEdge(adj,3,4);addEdge(adj,3,7);addEdge(adj,4,5);addEdge(adj,4,6);addEdge(adj,4,7);addEdge(adj,5,6);addEdge(adj,6,7);int source =0, dest =7;printShortestDistance(adj, source, dest,V);/**
* Shortest path length is: 2
* Path is ::
* 0 3 7
*/}}