我在编码以获得最小生成树时遇到了一些异常问题。
错误消息类似于:线程“main”中的异常 java.lang.ArrayIndexOutOfBoundsException: 1 at Assignment.RandomGraph.main(RandomGraph.java:36)
import java.util.*;
public class RandomGraph
{
public static Scanner br = new Scanner(System.in);
static int w [][];//it represents the weight between every two nodes.
static int n;//number of the vertices that you typed.
static int i, j;
static int visited[] = new int[n];
static int next[] = new int[n];
static int d[]=new int[n];
public static void main (String[] args)
{
System.out.println("Find the shortest edge");
System.out.println("\nEnter the number of the vertices: ");
n = br.nextInt();
w = new int[n][n];
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
{
if((i!=j))
{
w[i][j] = w[j][i]= 1+(int)(Math.random()*9);
}
else if(i == j)
{
w[i][j] = w[j][i] = 0;
}
}
for(i=1;i<=n;i++)
{
next[i]=visited[i]=0;
d[i]=32767;
}
Graph();
Prim();
}
static void Graph()
{
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
System.out.print(" "+w[i][j]+" ");
}
System.out.println();
}
}
static void Prim()
{
int current=1;
int total=1;
int mincost;
d[current]=0;
visited[current]=1;
do{
for(i=1;i<=n;i++)
{
if((w[current][i]!=0)&&(visited[i]==0)&&(w[current][i]<d[i]))
{
d[i]=w[current][i];
next[i]=current;
}
}
mincost = 32767;
for(i=1;i<=n;i++)
{
if((visited[i]==0)&&d[i]<mincost)
{
mincost=d[i];
current=i;
}
}
visited[current]=1;
total++;
}while(total!=n);
mincost=0;
for(i=1;i<=n;i++)
{
mincost=mincost+d[i];
System.out.print("\n Minimum cost = "+mincost);
System.out.print("\n Minimum Spanning tree is ");
}
for(i=1;i<=n;i++)
{
System.out.print("\n"+i+" to "+next[i]);
}
}
}