Skip to content

892. Surface Area of 3D Shapes 👎

  • Time:
  • Space:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
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;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
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;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
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