拓扑排序+最短路径(无环加权有向图最短路径算法)

特点:
       1、线性时间内解决单点最短路径问题
       2、能够处理负权边问题
       3、能够找出最长路径
不足:因为是基于拓扑排序的,所以不能解决带环的问题 

import java.util.ArrayList;
import java.util.Scanner;
import java.util.Stack;

import Graph.HasCycle;

public class TopDij {
	static boolean[]visit;
	static boolean[]onStack;
	static Stack<Integer> stack;
	static int n, m;
	static boolean hasCycle = false;
	static int[]dis;
	static int INF = 99999999;
	static ArrayList<EdgeS> []adj;
	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		n = in.nextInt();
		m = in.nextInt();
		visit = new boolean[n+1];
		adj = new ArrayList[n+1];
		stack = new Stack<>();
		dis = new int[n+1];
		onStack = new boolean[n+1];
		for(int i = 1; i <= n; i++ ) {
			adj[i] = new ArrayList<>();
		}
		for(int i = 0; i < m; i++ ) {
			int from = in.nextInt();
			int to = in.nextInt();
			int w = in.nextInt();
			adj[from].add(new EdgeS(from, to, w));
		}
		bfs(1);
//		while(!stack.isEmpty()) {
//			System.out.println(stack.pop() + " ");
//		}
		if(!hasCycle) {
			shortPath(1);
			
			for(int i = 1; i <= n; i++ ) {
				System.out.println(dis[i] + " ");
			}
		}
		else {
			System.out.println("hasCycle");
		}
	}
	public static void shortPath(int s) {
		for(int i = 1; i <= n; i++ ) {
			dis[i] = 99999999;
		}
		dis[s] = 0;
		while(!stack.isEmpty()) {
			int cur = stack.pop();
			for(EdgeS e: adj[cur]) {
				if(dis[e.to] > dis[cur] + e.w) {
					dis[e.to] = dis[cur] + e.w;
				}
			}
		}
		
	}
	public static void bfs(int cur) {// 进行拓扑排序的同时检查是否含有环 有环的话就退出
		visit[cur] = true;
		onStack[cur] = true;
		for(EdgeS e:adj[cur]) {
			if(!visit[e.to]) {
				bfs(e.to);
			}
			else if(onStack[e.to]){
				hasCycle = true;
				return;
			}
		}
		onStack[cur] = false;
		stack.push(cur);//记录拓扑排序结果 、逆后序
	}
}
class EdgeS{
	int from, to, w;
	public EdgeS(int f, int t, int w) {
		from = f;
		to = t;
		this.w = w;
	}
}

    原文作者:拓扑排序
    原文地址: https://blog.csdn.net/Tianweidadada/article/details/78635932
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞