单源最短路径,关于这个问题的贪心算有点不好理解,分析后续补充,代码也需要后续优化,便于理解
package test;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Created by saishangmingzhu on 2018/12/3.
* 单源最短路径
*/
public class SingleSourceShortestPath {
public static void main(String[] arg) {
new SingleSourceShortestPath().greedy();
}
/**
* 贪心算法
*/
public void greedy(){
//【1】创建有向图
List<Point> pointList=new ArrayList<>();
pointList.add(new Point("A",0));
pointList.add(new Point("B",1));
pointList.add(new Point("C",2));
pointList.add(new Point("D",3));
pointList.add(new Point("E",4));
Map<String,Integer> pathMap=new HashMap<>();
pathMap.put("AB",10);
pathMap.put("AD",30);
pathMap.put("AE",100);
pathMap.put("BC",50);
pathMap.put("CE",10);
pathMap.put("DC",20);
pathMap.put("DE",60);
//【2】从源顶点计算距离
// 源顶点为A
int[] dist=new int[pointList.size()];
for (int i=1;i<dist.length;i++){
dist[i]=Integer.MAX_VALUE;
}
List<Point> resultList=new ArrayList<>();
Point first=pointList.get(0);
pointList.remove(0);
while (pointList.size()>0){
int min=10000;
Point minP=null;
for (int i=0;i<pointList.size();i++) {
Point p = pointList.get(i);
String key = first.getName() + p.getName();
if (pathMap.containsKey(key)) {
int v = pathMap.get(key);
if (dist[p.getIndex()] > v + dist[first.getIndex()]) {
dist[p.getIndex()] = v + dist[first.getIndex()];
if (min>v + dist[first.getIndex()]){
min=v + dist[first.getIndex()];
minP=p;
}
}
}
else {
if (min>dist[p.getIndex()]){
min=dist[p.getIndex()];
minP=p;
}
}
}
resultList.add(minP);
pointList.remove(minP);
first=minP;
}
for (int i:dist)
System.out.println(i);
}
}
class Point{
String name;
int index;
public Point(String name, int index) {
this.name = name;
this.index = index;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getIndex() {
return index;
}
public void setIndex(int index) {
this.index = index;
}
}
©著作权归作者所有:来自51CTO博客作者塞上名猪的原创作品,如需转载,请注明出处,否则将追究法律责任
共同学习,写下你的评论
评论加载中...
作者其他优质文章