这是我获取最短路径的代码
static void shortestPath(int[][] adjacencyMatrix, int src, int dest) {
int n = adjacencyMatrix[0].length;
int[] shortest = new int[n];
boolean[] added = new boolean[n];
for (int v = 0; v < n;v++) {
shortest[v] = Integer.MAX_VALUE;
added[v] = false;
}
shortest[src] = 0;
int[] parents = new int[n];
parents[src] = NO_PARENT;
for (int i = 1; i < n; i++) {
int v1 = -1; //store temp data
int min = Integer.MAX_VALUE;
for (int v = 0; v < n; v++) {
if (!added[v] && shortest[v] < min) {
v1 = v;
min = shortest[v];
}
}
added[v1] = true; // ERROR HAPPENS HERE
for (int v = 0; v < n; v++) {
int dist = adjacencyMatrix[v1][v];
if (dist > 0 && ((min + dist) <shortest[v])){
parents[v] = v1;
shortest[v] = min + dist;
}
}
}
dists.add(shortest[dest]);
visitUtil(dest, parents);
}
static void visitUtil(int i,int[] parents) {
if (i == NO_PARENT)
return;
visitUtil(parents[i], parents);
edges.add(i);
}
我的矩阵是这个
{ 0,10, 0, 0, 3 },
{0, 0, 5, 0, 1 },
{ 0, 0, 0, 7, 8 },
{ 0, 0, 0, 0, 2 },
{ 0, 0, 0, 0, 0 }
这是我的图表,所以您可以看到它。
我得到一个ArrayIndexOutOfBoundsException。例如,假设我要从2-4开始,在下图中,您可以看到权重为8,它们直接相连。
我该如何解决?