编号三角形从上到下

时间:2015-04-05 20:25:57

标签: java methods multidimensional-array max min

下面我试图想出一个方法来找出找出最短路径的路径,但每次运行程序时,我都会在int cols = myArray [rows] .length的findshortestPath1上得到一个nullpointer异常。不知道如何解决这个问题。如果您有其他方法我可以尝试解决这个问题,我会非常感激。

*******更新*******好的我用你的建议更新了这段代码,但我仍然遇到了问题

minCosts[0] = myArray[row][col]

findShortestPath(myArray, minCosts, row, col);

代码:

import java.util.Random;


public class Triangle{

 public static void createTriangle(int numRows){

     int rows=numRows;
     int max =9, min =2;
     int[][] myArray = new int[rows][];
     Random random = new Random();

for (int i = 0; i < rows; i++) {

myArray[i]= new int[i+1];


//Below is used for organizing the triangle
System.out.println("");
for(int p=rows-i; p>0;p--)
System.out.print(" ");

for (int j = 0; j <=i; j++) {

//below puts the spacing between each column in the triangle
System.out.print(" ");



myArray[i][j] = random.nextInt(max - min + 1) + min;

System.out.print(myArray[i][j]);
    System.out.print(" ("+i+", "+j+") ");
 }
 }
 }

public static int findShortestPath1(int numRows) {


     int rows= numRows;
     int[][] myArray = new int[rows][];

     int numNodes = sumToN(rows);
     int[] minCosts = new int[numNodes];

     for(int row = 0; row<rows; row++) {
         int cols = new int[rows].length;

     for(int col = 0; col< cols; col++) {
         findShortestPath(myArray, minCosts, row, col);
     }
     }





 int row = rows;
 int cols = new int[rows].length;
 int min1 = -1;

 for(int col = 0; col<cols; col++) {
  int cost = minCosts[indexFromRowCol(rows,col)];

  if(cost < min1 || min1 ==-1) {
      min1 = cost;
  }
  }

  return Math.max(0, min1);
  }



  private static int findShortestPath(int[][] myArray, int[] minCosts, int        row, int col) {
if (row == 0) {
    minCosts[0] = myArray[row][col];
    return minCosts[0];
}

int minValue = -1;

if (col - 1 >= 0) {
    minValue = minCosts[indexFromRowCol(row - 1, col - 1)];
}

if (col < myArray[row - 1].length) {
    int cost = minCosts[indexFromRowCol(row - 1, col)];

    if (minValue == -1) {
        minValue = cost;
    }

    minValue = Math.min(minValue, cost);
}

int minCost = myArray[row][col] + minValue;
minCosts[indexFromRowCol(row, col)] = minCost;

return minCost;
}

private static int sumToN(int n) {
if (n < 0) {
    return 0;
}
return n * (n + 1) / 2;
}

private static int indexFromRowCol(int row, int col) {
return sumToN(row) + col; 

}    }

1 个答案:

答案 0 :(得分:0)

此:

for(int row = 0; row >= rows; row++)

应该是:

for(int row = 0; row < rows; row++)

例如,假设rows = 10。然后row >= rows相当于0 >= 10,即false,因此for循环永远不会运行。

当你这样做时:

int row = rows - 1;
int cols = myArray[row].length;

您将获得row = 9但是,由于for循环未执行,myArray仍为空。因此,当您尝试访问NullPointerException时,您会收到myArray[9].length

另一个问题是,因为你没有初始化第二个维度的大小:

int[][] myArray = new int[rows][];

当您尝试执行此操作时,您仍会在NullPointerException循环中获得for

int cols = myArray[row].length;

因此,您可能希望在myArray中初始化findShortestPath1(),就像在createTriangle()中一样。