To find the minimum start & end point of a n*n matrix, i.e. distance between (0, 0) & (n-1, n-1). Value at each block represents the cost.
public class Paths {
public static void main(String[] args) {
int[] input2 = {5,7,4,6,2,3,5,1,3,1,9,7,1,6,8,8};
int[] input1 = {4,4};
System.out.println("Minimum cost : " + no_of_path(input1, input2));
}
public static int no_of_path(int[] input1,int[] input2)
{
int[][] arr = new int[input1[0]][input1[1]];
int k = 0;
for(int i = 0; i < input1[0]; i++){
for(int j = 0; j < input1[1]; j++){
arr[i][j] = input2[k];
k++;
}
}
int cost = paths(arr, 0, 0, input1[0], input1[1]);
return cost;
}
public static int paths(int[][] arr, int i, int j, int row, int col){
int c = 0;
int d = 0;
int r = 0;
if(i == row-1 && j == col-1)
return arr[i][j];
if(i < row && j+1 < col){
c = paths(arr, i, j+1, row, col);
c = c + arr[i][j];
}
if(i+1 < row && j+1 < col){
d = paths(arr, i+1, j+1, row, col);
d = d + arr[i][j];
}
if(i+1 < row && j < col){
r = paths(arr, i+1, j, row, col);
r = r + arr[i][j];
}
if(c ==0 || d == 0 || r == 0)
return c+d+r;
else if(c <= d && c <=r)
return c;
else if(d <= c && d <=r)
return d;
else if(r <= c && r <=d)
return r;
else
return 0;
}
}
public class Paths {
public static void main(String[] args) {
int[] input2 = {5,7,4,6,2,3,5,1,3,1,9,7,1,6,8,8};
int[] input1 = {4,4};
System.out.println("Minimum cost : " + no_of_path(input1, input2));
}
public static int no_of_path(int[] input1,int[] input2)
{
int[][] arr = new int[input1[0]][input1[1]];
int k = 0;
for(int i = 0; i < input1[0]; i++){
for(int j = 0; j < input1[1]; j++){
arr[i][j] = input2[k];
k++;
}
}
int cost = paths(arr, 0, 0, input1[0], input1[1]);
return cost;
}
public static int paths(int[][] arr, int i, int j, int row, int col){
int c = 0;
int d = 0;
int r = 0;
if(i == row-1 && j == col-1)
return arr[i][j];
if(i < row && j+1 < col){
c = paths(arr, i, j+1, row, col);
c = c + arr[i][j];
}
if(i+1 < row && j+1 < col){
d = paths(arr, i+1, j+1, row, col);
d = d + arr[i][j];
}
if(i+1 < row && j < col){
r = paths(arr, i+1, j, row, col);
r = r + arr[i][j];
}
if(c ==0 || d == 0 || r == 0)
return c+d+r;
else if(c <= d && c <=r)
return c;
else if(d <= c && d <=r)
return d;
else if(r <= c && r <=d)
return r;
else
return 0;
}
}