迪杰斯特拉算法
一、问题引出
二、介绍
三、算法过程
四、代码实现
package com.achang.algorithm;
import java.util.Arrays;
public class DijkstraAlgorithm {
public static void main(String[] args) {
char[] vertex = {'a', 'b', 'c', 'd', 'e', 'f', 'g' };
final int N = 65535;
int[][] matrix = {
{N, 5, 7, N, N, N, 2},
{5, N, N, 9, N, N, 3},
{7, N, N, N, 8, N, N},
{N, 9, N, N, N, 4, N},
{N, N, 8, N, N, 5, 4},
{N, N, N, 4, 5, N, 6},
{2, 3, N, N, 4, 6, N},
};
Graphs graphs = new Graphs(vertex, matrix);
graphs.list();
graphs.dsj(6);
System.out.println("==========如下为结果=========");
graphs.showResult();
}
}
class VisitedVertex{
public int[] alreadyArr;
public int[] preVisited;
public int[] disArr;
public VisitedVertex(int length,int index){
this.alreadyArr = new int[length];
this.preVisited = new int[length];
this.disArr = new int[length];
Arrays.fill(disArr,65535);
this.alreadyArr[index] = 1;
this.disArr[index] = 0;
}
public boolean in(int index){
return alreadyArr[index] == 1;
}
public void updateDis(int index,int length){
this.disArr[index] = length;
}
public void updatePre(int index,int pre){
this.preVisited[pre] = index;
}
public int getDis(int index){
return disArr[index];
}
public int updateArr(){
int min = 65535,index = 0;
for (int i = 0; i < alreadyArr.length; i++) {
if (alreadyArr[i] == 0 && disArr[i] < min){
min = disArr[i];
index = i;
}
}
alreadyArr[index] = 1;
return index;
}
public void showResult(){
System.out.println("preVisited:"+Arrays.toString(preVisited));
System.out.println("alreadyArr:"+Arrays.toString(alreadyArr));
System.out.println("disArr:"+Arrays.toString(disArr));
}
}
class Graphs {
private char[] vertex;
private int[][] matrix;
private VisitedVertex vv;
public Graphs(char[] vertex, int[][] matrix) {
this.vertex = vertex;
this.matrix = matrix;
}
public void list() {
for (int[] ints : matrix) {
System.out.println(Arrays.toString(ints));
}
}
public void showResult(){
vv.showResult();
}
public void dsj(int index){
vv = new VisitedVertex(vertex.length, index);
update(index);
for (int i = 1; i < vertex.length; i++) {
index = vv.updateArr();
update(index);
}
}
private void update(int index){
int len = 0;
for (int i = 0; i < matrix[index].length; i++) {
len = vv.getDis(index) + matrix[index][i];
if (!vv.in(i) && len < vv.getDis(i)){
vv.updatePre(i,index);
vv.updateDis(i,len);
}
}
}
}
|