Surface Area of 3D Shapes

You are given an n x n grid where you have placed some 1 x 1 x 1 cubes. Each value v = grid[i][j] represents a tower of v cubes placed on top of the cell (i, j).

After placing these cubes, you have decided to glue any directly adjacent cubes to each other, forming several irregular 3D shapes.

Return the total surface area of the resulting shapes.

Note: The bottom face of each shape counts toward its surface area.

Example:

Input: grid = [[1,2],[3,4]]
Output: 34

Approach

C++

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

int surfaceArea(vector<vector<int>> &grid)
{
    int cube = 0sf = 0;
    for (int i = 0i < grid.size(); ++i)
    {
        for (int j = 0j < grid[0].size(); ++j)
        {

            //if grid at current position is zero
            //then continue
            if (grid[i][j] == 0)
            {
                continue;
            }

            //update cube value
            cube += grid[i][j];

            //update surface area
            //-1 for top
            sf += grid[i][j] - 1;

            //now update surface area
            if (j + 1 < grid[0].size())
            {
                sf += min(grid[i][j]grid[i][j + 1]);
            }

            //updare surface area
            if (i + 1 < grid.size())
            {
                sf += min(grid[i][j]grid[i + 1][j]);
            }
        }
    }
    return cube * 6 - sf * 2;
}
int main()
{
    vector<vector<int>> grid = {{12}, {34}};

    cout << surfaceArea(grid);

    return 0;
}


No comments:

Post a Comment