/Min Cost Path

Min Cost Path

Min Cost Path

public class MinCostPath {

    public static void main(String args[]) {
        int a[][] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
        printArray(a);
        System.out.println("Min Cost : " + mincostpath(a));
    }

    private static void printArray(int a[][]) {
        for (int i = 0; i < a.length; i++) {
            for (int j = 0; j < a[0].length; j++) {
                System.out.print(a[i][j] + " ");
            }
            System.out.println();
        }
    }

    private static int mincostpath(int a[][]) {
        return mincostpath(a, 0, 0);
    }

    private static int mincostpath(int a[][], int i, int j) {
        int m = 3;
        int n = 3;

        if (i == m - 1 && j == n - 1) {
            return a[i][j];
        }

        if (i >= m || j >= n) {
            return Integer.MAX_VALUE;
        }

        int a1 = mincostpath(a, i + 1, j);
        int a2 = mincostpath(a, i + 1, j + 1);
        int a3 = mincostpath(a, i, j + 1);

        return (a[i][j] + (Math.min(a1, Math.min(a2, a3))));
    }
}