编号三角形从上到下

Top to bottom for numbered triangle

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

*****更新******* 好的,我根据您的建议更新了该代码,但我在

时仍然遇到问题
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; 

} }

这个:

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 仍然是空的。因此,当您尝试访问 myArray[9].length.

时,您会得到一个 NullPointerException

另一个问题是,由于您在初始化时没有初始化第二个维度的大小:

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

当您尝试这样做时,您仍然会在 for 循环中得到一个 NullPointerException

int cols = myArray[row].length;

所以您可能想在 findShortestPath1() 中初始化 myArray,就像在 createTriangle() 中一样。