62,625
社区成员
发帖
与我相关
我的任务
分享public class Test
{
class HighCost
{
public HighCost()
{
highcost=0;
belong=0;
}
public double highcost;
public int belong;
}
public void prim(double [][]matrix, int length)
{
HighCost [] treenodes =new HighCost[length];
int index=0;
int flag=0;
double max=0;
double [] nodes=new double[length];
for(int i=0;i<length;i++)
{
treenodes[i].highcost=matrix[0][i]; //空指针异常
treenodes[i].belong=index; //空指针异常
}
nodes[index]=-1;
index++;
for(int l=0;l<length;l++)
{
for(int j=0;j<length;j++)
{
if(treenodes[j].highcost>max)
{
flag = j;
max = treenodes[j].highcost;
nodes[index] = treenodes[j].belong;
}
}
index++;
for(int k=0;k<length;k++)
{
if(matrix[flag][k]>treenodes[k].highcost)
{
treenodes[k].highcost = matrix[flag][k]; //空指针异常
treenodes[k].belong=flag; //空指针异常
}
}
}
for(double m:nodes)
{
System.out.println(m);
}
} public static void main(String[] args) throws Exception
{
double[][] matrix =new double[][]
{{0,1,3,2},
{1,0,4,1},
{3,4,0,5},
{2,1,5,0}};
new Test().prim(matrix,matrix.length);
}
另外,我定义内部类的时候已经把belong和highcost等于0了呀,初始化后的数组难道不应该是是n个HighCost对象,里面的highcost和belong不是等于0吗?谢谢 public static void main(String[] args) throws Exception
{
double[][] matrix =new double[][]
{{0,1,3,2},
{1,0,4,1},
{3,4,0,5},
{2,1,5,0}};
new Test().prim(matrix,matrix.length);
}
另外,我定义内部类的时候已经把belong和highcost等于0了呀,初始化后的数组难道不应该是是n个HighCost对象,里面的highcost和belong不是等于0吗?谢谢[/quote]
HighCost [] treenodes =new HighCost[length]; 看这句话.你贴出来的代码的21行. 你的代码一直在用这个数组啊.
好吧.. 如果你不明白的话.. 这样说吧, 你要循环一下 然后把数组每个下标对应的值都填充成一个 new HighCost()