求解最短路径Bellman_Ford 算法优化版——结合队列


import java.util.*;
public class Main {
	static Scanner in  = new Scanner(System.in);
	static int INF = 99999999;
    static int[] dis = new int[100];
    static int[] bck= new int[100];
    static int[] v = new int[100];
    static int[] u= new int[100];
    static int[] w = new int[100];
    static int[] first = new int[100];
    static int[] next = new int[100];
	static int[] bool = new int[100];
	static int n,m,k;
	//使用first和next数组来实现链表
	public static void main(String[] args) {	
		while(in.hasNext()){
			Queue<Integer> que = new LinkedList<>();
			Arrays.fill(bool, 0);
			n = in.nextInt();
			m = in.nextInt();			
	   for (int i = 1; i <= n; i++) {
				dis[i]=INF;
				first[i]=-1;
			}
	    dis[1]=0;
		for (int i = 1; i <= m; i++) {
			u[i]=in.nextInt();
			v[i]=in.nextInt();
			w[i]=in.nextInt();
			//实现链表的关键代码,手写过程即可明白
			next[i]=first[u[i]];
			first[u[i]]=i;
			
		}
		//1入队
		que.add(1);
		bool[1]=0;
		while(que.size()!=0){
			k=first[que.peek()];//获取要处理队首顶点
			while(k!=-1){
				if(dis[v[k]]>dis[u[k]]+w[k]){
					dis[v[k]]=dis[u[k]]+w[k];
					if(bool[v[k]]==0){
						que.add(v[k]);
						bool[v[k]]=1;
					}
				}
			   k=next[k];//移动链表指针
			}
		 bool[que.peek()]=0;//以后可能再次用到
		  que.poll();	//出队  
		}
		for (int i = 1; i <= n; i++) {
			System.out.print(dis[i]+" ");
		}
	 }
  }
}



//结果示例
//5 7
//1 2 2
//1 5 10
//2 3 3
//2 5 7 
//3 4 4
//4 5 5
//5 3 6
//0 2 5 9 9 









    原文作者:Bellman - ford算法
    原文地址: https://blog.csdn.net/JingleLiA/article/details/78011948
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞