# dijkstra算法

``````public class DijkstraAlgorithm {
public static void main(String[] args) {
char[] vertex = { ‘A‘, ‘B‘, ‘C‘, ‘D‘, ‘E‘, ‘F‘, ‘G‘ };
int[][] matrix = new int[vertex.length][vertex.length];
final int N = 65535;
matrix[0] = new int[] { N, 5, 7, N, N, N, 2 };
matrix[1] = new int[] { 5, N, N, 9, N, N, 3 };
matrix[2] = new int[] { 7, N, N, N, 8, N, N };
matrix[3] = new int[] { N, 9, N, N, N, 4, N };
matrix[4] = new int[] { N, N, 8, N, N, 5, 4 };
matrix[5] = new int[] { N, N, N, 4, 5, N, 6 };
matrix[6] = new int[] { 2, 3, N, N, 4, 6, N };
Graph graph = new Graph(vertex, matrix);
graph.showGraph();
graph.dsj(0);
graph.showDijkstra();
}
}
``````

Graph类：

``````class Graph {
private char[] vertex;// 顶点数组
private int[][] matrix;// 邻接矩阵
private VisitedVertex vv;//表示已经访问的顶点的集合

public Graph(char[] vertex, int[][] matrix) {//构造器
this.matrix = matrix;
this.vertex = vertex;
}

public void showGraph() {
for (int[] link : matrix) {
}
}
/**
* 算法实现
* @param index 表示出发顶点对应的下标
*/
public void dsj(int index) {
vv = new VisitedVertex(vertex.length, index);
update(index);//更新index顶点到周围顶点的距离和前驱顶点
for(int j = 1; j < vertex.length; j++) {
index = vv.updateArr();//选择并返回新的访问顶点
update(index);
}
}

//更新index下标顶点到周围顶点的距离和周围顶点的前驱节点
private void update(int index) {
int len = 0;//出发顶点到index顶点的距离 + 从index顶点到j顶点的距离的和
for(int j = 0; j < matrix[index].length; j++) {
len = vv.getDis(index) + matrix[index][j];
//j未被访问且len小于出发顶点到j顶点的距离，就需要更新
if(!vv.in(j) && len < vv.getDis(j)) {
vv.updatePre(j, index);
vv.updateDis(j, len);
}
}
}

public void showDijkstra() {
vv.show();
}
}
``````

``````//已访问顶点集合
class VisitedVertex {
public int[] pre_vistied;// 每个下标对应的值为前一个顶点下标，会动态更新
public int[] dis;// 记录出发顶点到其他所有顶点的距离，会动态更新

public VisitedVertex(int length, int index) {// 顶点的个数，出发顶点对应的下标
this.pre_vistied = new int[length];
this.dis = new int[length];
Arrays.fill(dis, 65535);//初始化
this.dis[index] = 0;// 设置出发顶点的访问距离为0
}

/**
* 判断index顶点是否被访问过
*
* @param index
* @return 如果访问过就返回true，否则返回false
*/
public boolean in(int index) {
}

/**
* 更新出发顶点到index顶点的距离
*
* @param index
* @param len
*/
public void updateDis(int index, int len) {
dis[index] = len;
}

/**
* 更新顶点的前驱为index节点
*
* @param pre
* @param index
*/
public void updatePre(int pre, int index) {
pre_vistied[pre] = index;
}
/**
* 返回出发顶点到index顶点的距离
* @param index
* @return
*/
public int getDis(int index) {
return dis[index];
}

//继续选择并返回新的访问顶点
public int updateArr() {
int min = 65535;
int index = 0;
for(int i = 0; i < already_arr.length; i++) {
if(already_arr[i] == 0 && dis[i] < min) {
min = dis[i];
index = i;
}
}
return index;
}

//显示最后的结果
public void show() {
System.out.print(i + " ");
}
System.out.println();
for(int i : pre_vistied) {
System.out.print(i + " ");
}
System.out.println();
for(int i : dis) {
System.out.print(i + " ");
}
}
}
``````

dijkstra算法

(0)
(0)