3D Surface Area

Madison is a little girl who is fond of toys. Her friend Mason works in a toy manufacturing factory. Mason has a 2D board  of size  with  rows and  columns. The board is divided into cells of size  with each cell indicated by its coordinate (i,j. The cell  has an integer  written on it. To create the toy Mason stacks  number of cubes of size  on the cell .

Given the description of the board showing the values of  and that the price of the toy is equal to the 3d surface area find the price of the toy.

Example:

Input:  H = 3, W = 3, A = {{1, 3, 4}, {2, 2, 3}, {1, 2, 4}}
Output: 60

Approach

Java

public class SurfaceArea {
    public static void main(String[] args) {

        int H = 3;
        int W = 3;

        int[][] A = { { 134 }, { 223 }, { 124 } };

        System.out.println(surfaceArea(A));
    }

    static int surfaceArea(int[][] A) {
        int area = 0;
        for (int i = 0; i < A.length; i++) {
            for (int j = 0; j < A[0].length; j++) {
                area += (A[i][j] * 4) + 2;
                if (j >= 1)
                    area -= Math.min(A[i][j - 1], A[i][j]) * 2;
                if (i >= 1)
                    area -= Math.min(A[i - 1][j], A[i][j]) * 2;
            }
        }
        return area;
    }

}

C++

#include <bits/stdc++.h>
using namespace std;

int surfaceArea(vector<vector<int>> A)
{
    int area = 0;
    for (int i = 0i < A.size(); i++)
    {
        for (int j = 0j < A[0].size(); j++)
        {
            area += (A[i][j] * 4) + 2;
            if (j >= 1)
                area -= min(A[i][j - 1]A[i][j]) * 2;
            if (i >= 1)
                area -= min(A[i - 1][j]A[i][j]) * 2;
        }
    }
    return area;
}

int main()
{

    int H = 3;
    int W = 3;

    vector<vector<int>> A = {{134},
                             {223},
                             {124}};

    cout << surfaceArea(A<< "\n";
    return 0;
}


No comments:

Post a Comment