Dijkstra算法又叫作迪杰斯特拉算法,是利用"贪心法"(在对问题进行求解时,总是做出在当前看来最好的选择策略)设计算法的一个成功范例。
适用条件:带权无环和无负权值
举个栗子:
Dijkstra算法的代码实现如下:
package com.threeTop.www;
import java.util.Stack;
/**
* 邻接矩阵存储方式的Dijkstra算法
* @author wjgs
*
*/
public class Dijkstra {
//通过下标映射元素值
private int[] mapping;
//图的二维数组
private int[][] matrix;
/**
* 初始化图的顶点
* @param vertexes 顶点数组
*/
public Dijkstra(int []vertexes)
{
int length=vertexes.length;
mapping=new int[length];
matrix=new int[length][length]; //图的二维矩阵
for(int i=0;imapping.length-1||y>mapping.length-1)
{
throw new IndexOutOfBoundsException("边的顶点不存在!");
}
//增加边的权值
matrix[x][y]=value;
}
/**
* Dijkstra算法实现到各点的最短路径
* @param start
*/
public void dijkstra(int start)
{
int length =mapping.length;
int x=-1; //记录起始点
for(int i=0;i0)
{
path[i]=x;
}
else
{
//不可达,则赋前一个顶点下标为-1
path[i]=-1;
}
}
//先把起始顶点加入s
s[x]=1;
for(int i=0;istack=new Stack();
for(int i=0;i"+mapping[i]+" 最短路径长度:"+distance[x][i]);
//path存储路径,可以逆序输出,可以借助栈实现正序输出
System.out.print("逆序最短路径输出:");
int index=i;
while(index!=-1)
{
System.out.print(mapping[index]+" ");
stack.push(mapping[index]);
index=path[index];
}
System.out.print("正序最短路径输出:");
while(!stack.isEmpty())
{
System.out.print(stack.pop()+" ");
}
System.out.println();
}
}
}
public static void main(String[] args) {
int[] vetexes={1,2,3,4,5,6};
Dijkstra graph=new Dijkstra(vetexes);
graph.addEdge(1, 2,16);graph.addEdge(2, 1,16);
graph.addEdge(1, 3,1);graph.addEdge(3, 1,1);
graph.addEdge(1, 5,12);graph.addEdge(5, 1,12);
graph.addEdge(1, 6,15);graph.addEdge(6, 1,15);
graph.addEdge(2, 4,2);graph.addEdge(4, 2,2);
graph.addEdge(2, 6,8);graph.addEdge(6, 2,8);
graph.addEdge(3, 5,5);graph.addEdge(5, 3,5);
graph.addEdge(4, 6,3);graph.addEdge(6, 4,3);
graph.addEdge(5, 6,8);graph.addEdge(6, 5,8);
graph.addEdge(4, 5,9);graph.addEdge(5, 4,9);
graph.dijkstra(1);
}
}