1. 程式人生 > >Dijkstra、Bellman_Ford、SPFA、Floyd演算法複雜度比較

Dijkstra、Bellman_Ford、SPFA、Floyd演算法複雜度比較

package C24;

import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

import C22.GraphFactory;
import C22.Pair;
import C22.Weighted_Adjacent_List;

public class SPFA {
	public int[] spfa(Weighted_Adjacent_List G,String s){
		return spfa(G,G.getVertexIndex(s));
	}
	public int[] spfa(Weighted_Adjacent_List G,int s){
		//1.建立所要的資料結構
		int size = G.getSize();
		int d[] = new int[size];	//距離估計
		for(int i=0;i<d.length;i++){
			d[i] = Integer.MAX_VALUE;
		}
		List<Integer> Q = new LinkedList<Integer>();
		boolean is_in_queue[] = new boolean[size];	//是否在佇列中
		for(int i=0;i<is_in_queue.length;i++){
			is_in_queue[i] = false;
		}
		//2.初始化
		d[s] = 0;
		Q.add(s);
		is_in_queue[s] = true;
		//3.核心
		while(!Q.isEmpty()){
			int u = Q.remove(0);
			is_in_queue[u] = false;
			List<Pair> list = G.getListByVertexIndex(u);
			Iterator<Pair> iter = list.iterator();
			while(iter.hasNext()){
				Pair vstr = iter.next();
				int v = G.getVertexIndex(vstr.end);
				if(d[v]>d[u]+vstr.weight){
					d[v] = d[u] + vstr.weight;
					if(!is_in_queue[v]){	//如果鬆弛的點不在佇列中,則加入佇列;如果在佇列中,則不動
						Q.add(v);
						is_in_queue[v] = true;
					}
				}
			}
		}
		return d;
	}
	public static void main(String[] args) throws Exception {
		SPFA spfa_alg = new SPFA();
		Weighted_Adjacent_List g = GraphFactory.getWeightedAdjacentListInstance("input\\weighted_graph.txt");
		int[] d = spfa_alg.spfa(g,"s");
		for(int i=0;i<d.length;i++){
			System.out.println(g.getVertexValue(i)+":"+d[i]);
		}
	}
}