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 = 0, sf = 0;for (int i = 0; i < grid.size(); ++i){for (int j = 0; j < grid[0].size(); ++j){//if grid at current position is zero//then continueif (grid[i][j] == 0){continue;}//update cube valuecube += grid[i][j];//update surface area//-1 for topsf += grid[i][j] - 1;//now update surface areaif (j + 1 < grid[0].size()){sf += min(grid[i][j], grid[i][j + 1]);}//updare surface areaif (i + 1 < grid.size()){sf += min(grid[i][j], grid[i + 1][j]);}}}return cube * 6 - sf * 2;}int main(){vector<vector<int>> grid = {{1, 2}, {3, 4}};cout << surfaceArea(grid);return 0;}
No comments:
Post a Comment