Dijkstra(java实现)

本文介绍了一个使用Dijkstra算法寻找图中两点间最短路径的Java实现。通过自定义坐标值类与比较器,该程序能够接收用户输入的图结构,并输出从起点到终点的最短距离。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

还可以效率更好点:有时间修改(晚上写注释)

 

package com.bluebridge.org;

public class CoordinateValue {

	public CoordinateValue(int location,int value)
	{
		this.location=location;
		this.value=value;
	}
	int location;
	int value;
}


 

 

package com.bluebridge.org;

import java.util.Comparator;

public class CustomComparatpr implements Comparator<CoordinateValue> {

	@Override
	public int compare(CoordinateValue o1, CoordinateValue o2) {
		// TODO Auto-generated method stub
		//if(o1.location==o2.location)
			//return 0;
		if(o1.value<o2.value)
			return -1;
		else return 1;
	}

}


 

package com.bluebridge.org;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.Scanner;
import java.util.TreeSet;
public class ShortestPath {

	static int n;
	public  static void  main(String[] args)
	{
		Scanner scan=new Scanner(System.in);
		int value;
		n=scan.nextInt();
		TreeSet<Integer> set[]=new TreeSet[n+1];
		int map[][]=new int[n+1][n+1];
		for(int i=1;i<=n;i++)
		   Arrays.fill(map[i], -1);
		do
		{
			int i=scan.nextInt();
			int j=scan.nextInt();
			value=scan.nextInt();
			if(value>0)
			{
				if(set[i]==null)
					set[i]=new TreeSet<Integer>();
				set[i].add(j);
				map[i][j]=value;
			}
		}while(value>0);
		System.out.println(Dijkstra(map,set));
	}
	private static int Dijkstra(int map[][],TreeSet<Integer> set[])
	{
		boolean ans[]=new boolean[n+1];
		TreeSet<CoordinateValue> comSet=new TreeSet<CoordinateValue>(new CustomComparatpr());
		ArrayList<CoordinateValue> list=new ArrayList<CoordinateValue>();
		for(int i=1;i<=n;i++)
		{
			CoordinateValue value=new CoordinateValue(i,Integer.MAX_VALUE);
			comSet.add(value);
			list.add(value);
		}
		list.get(0).value=0;
		comSet.clear();
		comSet.addAll(list);
		Arrays.fill(ans,false);
		for(int i=1;i<n;i++)
		{
			CoordinateValue value=null;;
			Iterator<CoordinateValue> it=comSet.iterator();
			while(it.hasNext())
			{
				value=it.next();
				if(value.location!=n&&!ans[value.location]&&set[value.location]!=null)
				{
					break;
				}
			}
            ans[value.location]=true;
            Iterator<Integer> its=set[value.location].iterator();
            while(its.hasNext())
            {
            	  int location=its.next();
            	  CoordinateValue values=list.get(location-1);
            	  if(value.value+map[value.location][location]<values.value)
            	  {
            		  values.value=value.value+map[value.location][location];
            		  comSet.clear();
            		  comSet.addAll(list);
            	  }
            }
		}
		return list.get(n-1).value;
	}
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值