单源最短路径( Dijkstra算法)JAVA实现
package dijkstra;
public class Graph {
final int max=100;
public class VexNode{
int adjvex;
int data;
}
VexNode[] vexNodes;
int[] thevexs;
int[][] edges = new int[max][max];
public void createGraph(Graph graph,int[][] A,int[] vexs) {
thevexs=vexs;
for (int i = 0; i < vexs.length; i++) {
for (int j = 0; j < vexs.length; j++) {
graph.edges[i][j] = A[i][j];
}
}
}
public void printGraph(Graph graph) {
for (int i = 0; i < graph.thevexs.length; i++) {
for (int j = 0; j < graph.thevexs.length; j++) {
if (graph.edges[i][j]==1000) {
System.out.printf("%4s","/");
}else {
System.out.printf("%4d",graph.edges[i][j]);
}
}
System.out.println("\n");
}
}
}
package dijkstra;
public class DijkStra {
final int max = 100;
public static int[] Dijsktra(Graph graph,int start){
int n = graph.thevexs.length;
int[] shortPath = new int[n];
String[] path=new String[n];
for(int i=0;inew String(start+"-->"+i);
int[] visited = new int[n];
shortPath[start] = 0;
visited[start] = 1;
for(int count = 1;count <= n - 1;count++)
{
int k = -1;
int dmin = Integer.MAX_VALUE;
for(int i = 0;i < n;i++)
{
if(visited[i] == 0 && graph.edges[start][i]"k="+k);
shortPath[k] = dmin;
visited[k] = 1;
for(int i = 0;i < n;i++)
{
if(visited[i] == 0 && graph.edges[start][k] + graph.edges[k][i] < graph.edges[start][i]){
graph.edges[start][i] = graph.edges[start][k] + graph.edges[k][i];
path[i]=path[k]+"-->"+i;
}
}
}
for(int i=0;i"从"+start+"出发到"+i+"的最短路径为:"+path[i]);
System.out.println("=====================================");
return shortPath;
}
}
package dijkstra;
public class Test {
public static void main(String[] args) {
final int INF = 1000;
int[] vexs = {0,1,2,3,4,5};
int[][] A ={
{0,50,10,INF,INF,INF},
{INF,0,15,50,10,INF},
{20,INF,0,15,INF,INF},
{INF,20,INF,0,35,INF},
{INF,INF,INF,30,0,INF},
{INF,INF,INF,3,INF,0},
};
Graph graph = new Graph();
graph.createGraph(graph, A, vexs);
graph.printGraph(graph);
DijkStra dijkStra = new DijkStra();
int[] shortPath = dijkStra.Dijsktra(graph, 2);
for(int i = 0;i < shortPath.length;i++)
if (shortPath[i]!=INF) {
System.out.println("从"+"2"+"出发到"+i+"的最短距离为:"+shortPath[i]);
}
}
}