java实现dijkstra_Dijkstra(java实现)

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

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 {

@Override

public int compare(CoordinateValue o1, CoordinateValue o2) {

// TODO Auto-generated method stub

//if(o1.location==o2.location)

//return 0;

if(o1.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 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();

set[i].add(j);

map[i][j]=value;

}

}while(value>0);

System.out.println(Dijkstra(map,set));

}

private static int Dijkstra(int map[][],TreeSet set[])

{

boolean ans[]=new boolean[n+1];

TreeSet comSet=new TreeSet(new CustomComparatpr());

ArrayList list=new ArrayList();

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

{

CoordinateValue value=null;;

Iterator 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 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=value.value+map[value.location][location];

comSet.clear();

comSet.addAll(list);

}

}

}

return list.get(n-1).value;

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值