I'm writing a recursive method to find all the possible paths in a two dimensional array. From the top left point (0,0) to the bottom right point last point. And returns the sums of the paths.
public static void printPathWeights(int[][] m)
{
printPathWeights(m, 0, 0, 0);
}
public static void printPathWeights(int[][] m, int row, int col, int sum)
{
if(row == 0 && col ==0)
sum = 0;
if (row == m.length - 1 && col == m[row].length - 1)
System.out.println(sum);
else
{
if (row >= 0 && row < m.length && col >= 0 && col < m[row].length)
printPathWeights(m, row - 1, col, sum += m[row][col]); // Up
if (row >= 0 && row < m.length && col >= 0 && col < m[row].length)
printPathWeights(m, row + 1, col, sum += m[row][col]); // Down
if (row >= 0 && row < m.length && col >= 0 && col < m[row].length)
printPathWeights(m, row, col - 1, sum += m[row][col]); // Left
if (row >= 0 && row < m.length && col >= 0 && col < m[row].length)
printPathWeights(m, row, col + 1, sum += m[row][col]); // Right
}
}
currently my problem is that this function get into endless loop and not print my sum