Below I had tried to come up with a method to find the path to figure out the shortest path but every time I run the program I get a nullpointer exception at the findshortestPath1 at the int cols = myArray[rows].length I don't know how to solve this problem. If you have other methods I can try to solve this, tha twill be greatly appreciated.
*******UPDATE******* Okay I updated that code with your suggestions, but I was still getting problems at
minCosts[0] = myArray[row][col]
and
findShortestPath(myArray, minCosts, row, col);
Code:
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;
} }