Dijkstra算法应用了广度遍历,属于贪心算法
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class Djstl2 {
public const int infinity = 10000;
private int row = 6;
int[,] graph = new int[6, 6] {
{0, infinity, 10, infinity, 30, 100 },
{infinity, 0, 5, infinity, infinity, infinity },
{10, 5, 0, 50, infinity, infinity},
{infinity, infinity, 50, 0, 20, 10 },
{30, infinity, 50, 20, 0, 60 },
{100, infinity, infinity, 10, 60, 0 },
};
private List<int> listS;//已找到最短路径集合
private List<int> listU;//未找到点集合
private int[] distance;//原点到目标点的最小距离
private int[] pre;//最短路径点的上一个点
private bool[] isShortestPath;//是否确定为最短路径点
public Djstl2() {
listS = new List<int>(row);
listU = new List<int>(row);
distance = new int[row];
pre = new int[row];
isShortestPath = new bool[row];
}
public void Excute(int startIndex) {
listS.Add(startIndex);
isShortestPath[startIndex] = true;
//将剩余节点加入listU中
for (int i = 0; i < row; i++) {
if (i != startIndex) {
listU.Add(i);
}
distance[i] = graph[startIndex, i];
pre[i] = startIndex;
}
int count = listU.Count;
while (count > 0) {
int minIndex = listU[0];
//找到最小距离的点
for (int i = 0; i < listU.Count; i++) {
if (distance[minIndex] > distance[listU[i]] && isShortestPath[listU[i]] == false) {
minIndex = listU[i];
}
}
listS.Add(minIndex);
listU.Remove(minIndex);
isShortestPath[minIndex] = true;
//更新点的距离
for (int i = 0; i < listU.Count; i++) {
if (distance[listU[i]] > (distance[minIndex] + graph[minIndex, listU[i]])) {
distance[listU[i]] = distance[minIndex] + graph[minIndex,listU[i]];
pre[listU[i]] = minIndex;
}
}
count = listU.Count;
}
}
}