参考
https://blog.csdn.net/heroacool/article/details/51014824
https://www.cnblogs.com/mingjiatang/p/5974451.html
https://www.jianshu.com/p/ff6db00ad866
我这实现是有向图,无向图,可自行实现
实现
public class Dijkstra {
static int[][] source = {
{-1, -1, 10, -1, 30, 100},
{-1, -1, 5, -1, -1, -1},
{-1, -1, -1, 50, -1, -1},
{-1, -1, -1, -1, -1, 10},
{-1, -1, -1, 20, -1, 60},
{-1, -1, -1, -1, -1, -1},
};
public static String getMinDistance() {
Iterator<Map.Entry<String, Integer>> iterator = Umap.entrySet().iterator();
Map.Entry<String, Integer> minEntry = null;
while (iterator.hasNext()) {
Map.Entry<String, Integer> itempEntry = iterator.next();
if (minEntry == null || itempEntry.getValue() < minEntry.getValue()) {
minEntry = itempEntry;
}
}
// 数据清空
Umap.clear();
Smap.put(minEntry.getKey(), minEntry.getValue());
System.out.println(minEntry.toString());
return minEntry.getKey();
}
// u查找s数据
public static boolean find() {
if (sList.isEmpty()) {
sList.add(0);
}
for (int i = 0; i < sList.size(); i++) {
for (int j = 0; j < source.length; j++) {
String key = sList.get(i) + "->" + j;
String Rkey = j + "->" + sList.get(i);
if (source[sList.get(i)][j] != -1 && !(userPort.contains(key) || userPort.contains(Rkey))) {
Umap.put(key, source[sList.get(i)][j]);
}
}
}
System.out.println(Umap.toString());
String[] minIndex = getMinDistance().split("->");
System.out.println(Arrays.toString(sList.toArray()));
if (sList.contains(Integer.parseInt(minIndex[1]))) {
return false;
} else {
userPort.add(minIndex[0] + "->" + minIndex[1]);
userPort.add(minIndex[1] + "->" + minIndex[0]);
sList.add(Integer.parseInt(minIndex[1]));
return true;
}
}
// 最后的结果
public static Map<String, Integer> Smap = new HashMap<>();
// S到U的所有地距离
public static Map<String, Integer> Umap = new HashMap<>();
//已经使用的数据
public static List<Integer> sList = new ArrayList<>();
// 已使用坐标
public static List<String> userPort = new ArrayList<>();
public static void main(String[] args) {
boolean flag = true;
while (flag) {
flag = find();
System.out.println();
}
}
}
输出结果
1 s集合
2,s集合最小值
3,u集合
{0->5=100, 0->4=30, 0->2=10}
0->2=10
[0]
{0->5=100, 0->4=30, 2->3=50}
0->4=30
[0, 2]
{0->5=100, 4->3=20, 2->3=50, 4->5=60}
4->3=20
[0, 2, 4]
{0->5=100, 3->5=10, 2->3=50, 4->5=60}
3->5=10
[0, 2, 4, 3]
{0->5=100, 2->3=50, 4->5=60}
2->3=50
[0, 2, 4, 3, 5]