dijkstra算法JAVA实现

来源:互联网 发布:高速下载软件 编辑:程序博客网 时间:2024/06/05 17:33
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;


public class MyDijkstra2 {
private static final int INT_MIN = 0;
private static final int INT_MAX = Integer.MAX_VALUE;


private Map<Integer, Integer> distance = new HashMap<Integer, Integer>();
private Map<Integer, Integer> prevVertex = new HashMap<Integer, Integer>();


void Dijkstra(int numOfVertex, int startVertex, int[][] map)
{
Map<Integer, Boolean> isInS = new HashMap<Integer, Boolean>();
for (int k = 0; k < numOfVertex; k++)
isInS.put(k, false);
for (int i = 0; i < numOfVertex; ++i) {
distance.put(i, map[startVertex][i]);
if (map[startVertex][i] < INT_MAX)
prevVertex.put(i, startVertex);
else
prevVertex.put(i, -1);
}
prevVertex.put(startVertex, -1);/* 开始使用贪心思想循环处理不在S集合中的每一个节点 */
isInS.put(startVertex, true);
int u = startVertex;
for (int i = 1; i < numOfVertex; i++) // 这里循环从1开始是因为开始节点已经存放在S中了,还有numOfVertex-1个节点要处理
{
int nextVertex = u;
int tempDistance = INT_MAX;
for (int j = 0; j < numOfVertex; ++j) {
if ((isInS.get(j) == false) && (distance.get(j) < tempDistance))// 寻找不在S集合中的distance最小的节点
{
nextVertex = j;
tempDistance = distance.get(j);
}
}
isInS.put(nextVertex, true);
u = nextVertex;// 下一次寻找的开始节点
for (int j = 0; j < numOfVertex; j++) {
if (isInS.get(j) == false && map[u][j] < INT_MAX) {
int temp = distance.get(u) + map[u][j];
if (temp < distance.get(j)) {
distance.put(j, temp);// distance[ j ] = temp;
prevVertex.put(j, u);// prevVertex[ j ] = u;
}
}
}
}


}


void print()
{
for (int j = 0; j < 5; ++j) 
{
int index = j;
ArrayList<Integer> trace = new ArrayList<Integer>();
while (prevVertex.get(index) != -1) 
{
trace.add(prevVertex.get(index));
index = prevVertex.get(index);// preVertex[index];
}


System.out.print("路径:");// cout << "路径:";
for (int q = trace.size()-1; q >=0; q--) {
// includeIDs+=pass.get(entry.getKey()).get(i)+",";
System.out.print(trace.get(q) + "->");
}
System.out.print(j);
System.out.println("距离是:" + distance.get(j));
}
}
public static void main(String[] args) {
int map[][] = { // 定义有向图也可以是无向图(对称矩阵)
{ INT_MIN, 10, 5, INT_MAX, 20 },
{ 10, INT_MIN, 2, 17, INT_MAX},
{ 5, 2, INT_MIN, INT_MAX, INT_MAX }, 
{ INT_MAX, 17, INT_MAX, INT_MIN, 8 },
{ 20, INT_MAX, INT_MAX, 8, INT_MIN } };
for (int i = 0; i < 5; ++i) {
MyDijkstra2 dj = new MyDijkstra2();
dj.Dijkstra(5, i, map);
dj.print();
}
}
}
0 0