java 最优路径_Java最优路径Dijkstra

public class Dijkstra {

public static void main(String[] args) {

//初始化节点数据

int[][] data =initMap();

//总节点数

int nodeSize = data[0].length;

//所有便利过的节点

boolean[] done =new boolean[nodeSize];

//0到个节点最短路径长度

int[] shortLine =new int[]{0, 99999, 99999, 99999, 99999, 99999, 99999};

Queue queue =new PriorityQueue<>(Comparator.comparingInt(value -> value.length));

//初始化0节点

queue.add(new Node(0, 0));

while (!queue.isEmpty()) {

Node node = queue.poll();

done[node.id] =true;

for (int index =1; index < nodeSize; index++) {

//说明node.id节点到不了index节点

if (data[node.id][index] ==0) {

continue;

}

//0节点通过node.id到index的长度

int totalLength = node.length + data[node.id][index];

if (!done[index] && shortLine[index] > totalLength ) {

shortLine[index] = totalLength;

queue.add(new Node(index, totalLength));

}

}

}

Arrays.stream(shortLine).forEach(System.out::println);

}

static class Node {

//存储当前节点的id

private int id;

//存储0节点到当前节点的距离

private int length;

Node(int id, int length) {

this.id = id;

this.length = length;

}

}

private static int[][]initMap() {

int[][] map =new int [7][7];

map[0][1]=12;map[0][2]=14;map[0][3]=16;

map[1][0]=12;map[1][3]=7;map[1][4]=10;

map[2][0]=14;map[2][3]=9;

map[3][0]=16;map[3][1]=7;map[3][2]=9;map[3][4]=6;map[3][5]=2;

map[4][1]=10;map[4][3]=6;map[4][5]=5;map[4][6]=3;

map[5][2]=8;map[5][4]=5;map[5][6]=4;map[5][3]=2;

map[6][4]=3;map[6][5]=4;

return map;

}

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值