Java图的最短路径

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;


public class ShortestPath
{
static class Cell //节点
{
int node;  //到达的节点
int weight;  //权值

public Cell(int node, int weight)
{
this.node = node;
this.weight = weight;
}
}

@SuppressWarnings({ "unchecked", "rawtypes" })
public static void main(String[] args)
{
List[] graph = new List[11];
for(int i = 0; i < graph.length; i ++)
{
graph[i] = new ArrayList<Cell>();
}
graph[0].add(new Cell(1, 3));
graph[0].add(new Cell(4, 1));
graph[1].add(new Cell(2, 1));
graph[1].add(new Cell(6, 3));
graph[1].add(new Cell(9, 4));
graph[1].add(new Cell(5, 5));
graph[1].add(new Cell(0, 3));
graph[2].add(new Cell(1, 1));
graph[2].add(new Cell(3, 1));
graph[2].add(new Cell(6, 7));
graph[3].add(new Cell(2, 1));
graph[3].add(new Cell(10, 2));
graph[4].add(new Cell(0, 1));
graph[4].add(new Cell(5, 2));
graph[5].add(new Cell(4, 2));
graph[5].add(new Cell(1, 5));
graph[5].add(new Cell(7, 2));
graph[5].add(new Cell(8, 3));
graph[6].add(new Cell(2, 3));
graph[6].add(new Cell(3, 7));
graph[7].add(new Cell(5, 2));
graph[8].add(new Cell(5, 3));
graph[9].add(new Cell(1, 4));
graph[10].add(new Cell(3, 2));

Map<Integer, Integer> map = new HashMap<Integer, Integer>();

while(true)
{
int min = Integer.MAX_VALUE; //最小边
int min_no = -1;  //最小边的顶点

for(int i = 0; i < graph[0].size(); i ++) //遍历与0号顶点邻接的点
{
Cell c = (Cell) graph[0].get(i);
if(map.get(c.node) == null && c.weight < min )
{
min_no = c.node;
min = c.weight;
}
}

Iterator<Integer> itea = map.keySet().iterator();
while(itea.hasNext())
{
int k = itea.next();
int v = map.get(k);

for(int i = 0; i < graph[k].size(); i ++) //查找Map里面存放的点的最短路径
{
Cell c = (Cell) graph[k].get(i);
if(map.get(c.node) == null && c.weight + v < min)
{
min_no = c.node;
min = c.weight + v;
}
}
}

if(min < Integer.MAX_VALUE) //如果最短路程经发生变化,则保存该路径
{
map.put(min_no, min);
}
else  //否则结束循环完成寻找最短路径
{
break;
}
}

System.out.println(map); //输出结果
}
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值