Minimum Sum Path In 3-D Array

Given a 3-D array arr[l][m][n], the task is to find the minimum path sum from the first cell of array to the last cell of array. We can only traverse to adjacent element, i.e., from a given cell (i, j, k), cells (i+1, j, k), (i, j+1, k) and (i, j, k+1) can be traversed, diagonal traversing is not allowed, We may assume that all costs are positive integers.

Examples:

Input : arr[][][]= { {{1, 2}, {3, 4}},
                     {{4, 8}, {5, 2}} };
Output : 9
Explanation : arr[0][0][0] + arr[0][0][1] + 
              arr[0][1][1] + arr[1][1][1]

Input : { { {1, 2}, {4, 3}},
          { {3, 4}, {2, 1}} };
Output : 7
Explanation : arr[0][0][0] + arr[0][0][1] + 
              arr[0][1][1] + arr[1][1][1]
public class solution {

    public int minPathSum(int arr[][][]) {
        int l = arr.length, m = arr[0].length, n = arr[0][0].length;
        int dp[][][] = new int[l][m][n];
        // Base case
        dp[0][0][0] = arr[0][0][0];

        // Building row edge
        for (int i = 1; i < l; i++)
            dp[i][0][0] = dp[i - 1][0][0] + arr[i][0][0];

        // Building column edge
        for (int j = 1; j < m; j++)
            dp[0][j][0] = dp[0][j - 1][0] + arr[0][j][0];

        // Building height edge
        for (int k = 1; k < n; k++)
            dp[0][0][k] = dp[0][0][k - 1] + arr[0][0][k];

        // Building row-col area
        for (int i = 1; i < l; i++)
            for (int j = 1; j < m; j++)
                dp[i][j][0] = Math.min(dp[i - 1][j][0], dp[i][j - 1][0]) + arr[i][j][0];

        // Building row-height area
        for (int i = 1; i < l; i++)
            for (int k = 1; k < n; k++)
                dp[i][0][k] = Math.min(dp[i - 1][0][k], dp[i][0][k - 1]) + arr[i][0][k];

        // Building col-height area
        for (int k = 1; k < n; k++)
            for (int j = 1; j < m; j++)
                dp[0][j][k] = Math.min(dp[0][j][k - 1], dp[0][j - 1][k]) + arr[0][j][k];

        // Building rest of the 3d cube
        for (int i = 1; i < l; i++)
            for (int j = 1; j < m; j++)
                for (int k = 1; k < n; k++)
                    dp[i][j][k] = Math.min(dp[i - 1][j][k], Math.min(dp[i][j - 1][k], dp[i][j][k - 1])) + arr[i][j][k];

        return dp[l - 1][m - 1][n - 1];
    }
}

Last updated