LeetCode Solutions
892. Surface Area of 3D Shapes
Time: Space:
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;
}
};
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;
}
}
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