SPFA的邻接表算法<java> 01

本文借鉴http://www.cnblogs.com/liuzhen1995/p/6535025.html 算法原理,想要理解SPFA的原理的话可以先去了解一下,这里提供的是一种基于邻接矩阵的SPFA实现代码,利用java语言。
package Dijkstra_有权_spfa;
/*
 *这个邻接矩阵 spfa 
 */
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;

public class My_spfa_邻接矩阵 {
	private static final int INF = Integer.MAX_VALUE;
	private int [][] weight;
	private int nodes;
	private boolean []flag ;
	public My_spfa_邻接矩阵(int [][] weight,int nodes)
	{
		this.weight=weight;
		this.nodes = nodes;	
	}
	
	public void getSpfa(int src,int [] dist,int [] path)
	{
		flag=new boolean [nodes];
		for(int i = 0;i <nodes;i++)
		{
			dist[i]=INF;
		
		}
		Queue<Integer> queue = new LinkedList<Integer>();
		queue.add(src);
		flag[src]= true;
		dist[src]= 0;
		while(!queue.isEmpty())
		{
			int out = queue.poll();
			for(int i = 0;i<nodes;i++)  // 对于第一个出队点的找所有相邻点 
			{
				if(weight[out][i]!=INF&&dist[i]>dist[out]+weight[out][i])   // 判断一波邻接点,哇,好厉害啊
				{
					dist[i]=dist[out]+weight[out][i];
					if(!flag[i])
					{
						queue.add(i);
						flag[i]=true;
						path[out]=i;
					}
				}
			}  
			flag[out]=false; //找出所有相邻点并更新最短距离后重置标志。
		}
		for(int i = 0;i<nodes;i++)
		{
			System.out.print("点"+i+"距离为"+dist[i] +"\n");
//			System.out.print(path[i]);
		}
		
	}

	public static void main(String[] args) {
		Scanner scan = new Scanner(System.in);
		int nodes = scan.nextInt();
		int edges = scan.nextInt();
		int [][]weight = new int[nodes][nodes];
		for (int i = 0; i < nodes; i++)
			for (int j = 0; j < nodes; j++) 
			{
				if(i==j)
				weight[i][j]=0;
				else
				weight[i][j] = INF;
			}
		int src, des, content;
		for (int i = 0; i < edges; i++) 
		{
			src = scan.nextInt();
			des = scan.nextInt();
			content = scan.nextInt();
			weight[src][des] = content;
//			weight[des][src] = content;  
		}
		int[] path = new int[nodes];
		int[] dist = new int[nodes];
		My_spfa_邻接矩阵 M = new My_spfa_邻接矩阵(weight, nodes);
		M.getSpfa(0,dist,path);
	}
}

猜你喜欢

转载自blog.csdn.net/weixin_38035852/article/details/65445225