读书人

写了个Dijkstra算法解决办法

发布时间: 2013-01-08 14:02:13 作者: rapoo

写了个Dijkstra算法
写得很烂,求指导


//import java.io.*;
/*
* Dijkstra algorithm for digraph
*/
public class Dijkstra {
public static void main(String[] args) {
new Dijkstra().run();
}

void run() {
n = 6;
m = 9;
// a graph
g = new int[n][n];
// initialization
for (int a = 0; a < n; a++) {
for (int b = 0; b < n; b++) {
g[a][b] = -1; // undefined
}
}
g[0][1] = 2;
g[0][2] = 4;
g[1][2] = 1;
g[1][4] = 2;
g[1][3] = 4;
g[2][4] = 3;
g[3][5] = 2;
g[4][3] = 3;
g[4][5] = 2;

s = 0;
d = 5;
// memory allocation
inS = new int[n];
dst = new int[n];
parent = new int[n];
isInfinite = new int[n];
int local_shortest_in_T = 0;
// int local_shortest;

// the first step
int i, j, k;
for (i = 0; i < n; i++) {
if (!(i == s)) {
isInfinite[i] = 1; // distance is incomparable
} else {
isInfinite[i] = 0; // distance is comparable
}
parent[i] = -1;
dst[i] = 0; // distance for each is initialized with zero
inS[i] = 0; // no vertex is in set S now, they are all in set T

}
// the second step
for (i = 0; i < n; i++) {
// select a vertex with the least distance from the set T
local_shortest_in_T = 10000000;
for (j = 0; j < n; j++) {
if (local_shortest_in_T > dst[j] && inS[j] == 0
&& isInfinite[j] != 1) {
local_shortest_in_T = dst[j];
local_shortest = j; // remember this vertex
}
}

// for(j=0;j<n;j++){
j = local_shortest;
for (k = 0; k < n; k++) {
if (g[local_shortest][k] != -1) {
if (inS[k] == 0) {
// update the distance of the vertices of T, which are connected to vertex local_shortest
if (dst[j] + g[j][k] < dst[k] && isInfinite[k] == 0) {
dst[k] = dst[j] + g[j][k];
parent[k] = j; // set the parent vertex of k with j
} else if (isInfinite[k] == 1) {
dst[k] = dst[j] + g[j][k];
isInfinite[k] = 0;
parent[k] = j;// set the parent vertex of k with j
}
}
}
}
inS[local_shortest] = 1;
}

System.out.printf("\n The graph is :\n");
for (i = 0; i < n; i++) {


for (j = 0; j < n; j++) {
System.out.printf("%d\t", g[i][j]);
}
System.out.println();
}

String mypath = new String();
int last = d;
while (last != -1) {
if (last == d) {
mypath = new Integer(last).toString() + "\n" + mypath;
} else {
mypath = new Integer(last).toString() + "," + mypath;
}
/*
* another kind of output.
* if(last!=s){ System.out.printf("%d <- ", last); } else{
* System.out.printf("%d\n", last); }
*/
last = parent[last];
}
System.out.println(mypath);
}

int n; // number of vertices
int m; // number of edges
int[][] g; // the graph
int[] inS; // whether a vertex is in Set S
int[] dst; // distance of a vertex from source vertex
int s; // source vertex
int d; // destination vertex
int[] parent; // father vertex of current vertex
int[] isInfinite; // whether the distance of a vertex is infinite large
int local_shortest;
}


[解决办法]
顶点的类呢?弧的类呢?怎么着也来点“面向对象”的思想吧!要不然我感觉不好理解啊!
你是用邻接矩阵做的吧?反正又不用求出度,个人还是喜欢用邻接表,感觉链表型的结构比二维数组好理解。

读书人网 >软件架构设计

热点推荐