892. Surface Area of 3D Shapes LeetCode Solution
In this guide, you will get 892. Surface Area of 3D Shapes LeetCode Solution with the best time and space complexity. The solution to Surface Area of D Shapes problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.
Table of Contents
- Problem Statement
- Complexity Analysis
- Surface Area of D Shapes solution in C++
- Surface Area of D Shapes solution in Java
- Surface Area of D Shapes solution in Python
- Additional Resources
Problem Statement of Surface Area of D 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 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 1:
Input: grid = [[1,2],[3,4]]
Output: 34
Example 2:
Input: grid = [[1,1,1],[1,0,1],[1,1,1]]
Output: 32
Example 3:
Input: grid = [[2,2,2],[2,1,2],[2,2,2]]
Output: 46
Constraints:
n == grid.length == grid[i].length
1 <= n <= 50
0 <= grid[i][j] <= 50
Complexity Analysis
- Time Complexity:
- Space Complexity:
892. Surface Area of 3D Shapes LeetCode Solution in C++
class Solution {
public:
int surfaceArea(vector<vector<int>>& grid) {
int ans = 0;
for (int i = 0; i < grid.size(); ++i)
for (int j = 0; j < grid.size(); ++j) {
if (grid[i][j])
ans += grid[i][j] * 4 + 2;
if (i > 0)
ans -= min(grid[i][j], grid[i - 1][j]) * 2;
if (j > 0)
ans -= min(grid[i][j], grid[i][j - 1]) * 2;
}
return ans;
}
};
/* code provided by PROGIEZ */
892. Surface Area of 3D Shapes LeetCode Solution in Java
class Solution {
public int surfaceArea(int[][] grid) {
int ans = 0;
for (int i = 0; i < grid.length; ++i)
for (int j = 0; j < grid.length; ++j) {
if (grid[i][j] > 0)
ans += grid[i][j] * 4 + 2;
if (i > 0)
ans -= Math.min(grid[i][j], grid[i - 1][j]) * 2;
if (j > 0)
ans -= Math.min(grid[i][j], grid[i][j - 1]) * 2;
}
return ans;
}
}
// code provided by PROGIEZ
892. Surface Area of 3D Shapes LeetCode Solution in Python
class Solution:
def surfaceArea(self, grid: list[list[int]]) -> int:
ans = 0
for i in range(len(grid)):
for j in range(len(grid)):
if grid[i][j]:
ans += grid[i][j] * 4 + 2
if i > 0:
ans -= min(grid[i][j], grid[i - 1][j]) * 2
if j > 0:
ans -= min(grid[i][j], grid[i][j - 1]) * 2
return ans
# code by PROGIEZ
Additional Resources
- Explore all LeetCode problem solutions at Progiez here
- Explore all problems on LeetCode website here
Happy Coding! Keep following PROGIEZ for more updates and solutions.