fork download
  1. class AllPathsPrinter {
  2.  
  3. int [][] array;
  4. int rowCount;
  5. int colCount;
  6.  
  7.  
  8. public AllPathsPrinter(int [][]array){
  9.  
  10. this.array = array;
  11. rowCount = array.length;
  12. colCount = array[0].length;
  13.  
  14. }
  15.  
  16.  
  17. public void printAllPaths(int currX, int currY, String path,int sum){
  18. if(currX == rowCount-1){
  19. for(int j=currY;j<=colCount-1;j++){
  20. sum+=array[currX][j];
  21. path = path + array[currX][j];
  22. }
  23. System.out.println("Path : " + path+" sum "+sum);
  24. return;
  25. }
  26.  
  27. if(currY == colCount-1){
  28. for(int i=currX;i<=rowCount-1;i++){
  29. sum+=array[i][currY];
  30. path = path + array[i][currY];
  31. }
  32. System.out.println("Path : " + path+"sum "+sum);
  33. return;
  34. }
  35. sum+=array[currX][currY];
  36. path = path + array[currX][currY];
  37. printAllPaths(currX+1, currY, path,sum);
  38. printAllPaths(currX, currY+1, path,sum);
  39. printAllPaths(currX+1, currY+1, path,sum);
  40.  
  41. }
  42.  
  43. public static void main(String args[]){
  44.  
  45. int [][] ar = new int[][]{{1, 2, 3}, {4, 5, 6}};
  46. AllPathsPrinter allPathsPrinter = new AllPathsPrinter(ar);
  47. allPathsPrinter.printAllPaths(0,0,"",0);
  48.  
  49.  
  50. }
  51.  
  52.  
  53. }
Success #stdin #stdout 0.1s 320576KB
stdin
Standard input is empty
stdout
Path : 1456 sum 16
Path : 1256 sum 14
Path : 1236sum 12
Path : 126 sum 9
Path : 156 sum 12