public class AllPos{
public static boolean valid(int[][] m,int row,int col){
if(row>=0 && row <m.length && col>=0 && col <m[row].length)
return true;
else return false;
}
public static void printPathWeights(int[][] m){
printPathWeights(m,0,0,0);//m,row,col.sum
}
public static void printPathWeights(int[][] m,int row,int col,int sum){
if(row == 0 && col ==0)
sum = 0;
if(m.length-1 == row && m[row].length-1 == col){
System.out.println(sum);
return;
}
else{
if(valid(m,row+1,col))
printPathWeights(m,row+1,col,sum+=m[row][col]); //down
if(valid(m,row,col+1))
printPathWeights(m,row,col+1,sum+=m[row][col]); //right
if((valid(m,row-1,col)) && (row < m.length-1))
printPathWeights(m,row,col-1,sum+=m[row][col]); //left
}
return;
}
public static void main (String args[]){
int [][] matrix = {{8,4,2,4,3},
{6,3,8,4,5},
{1,4,9,9,7},
{2,1,7,6,5}};
printPathWeights(matrix);
}
}