返回介绍

solution / 0800-0899 / 0892.Surface Area of 3D Shapes / README_EN

发布于 2024-06-17 01:03:33 字数 3890 浏览 0 评论 0 收藏 0

892. Surface Area of 3D Shapes

中文文档

Description

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

Solutions

Solution 1

class Solution:
  def surfaceArea(self, grid: List[List[int]]) -> int:
    ans = 0
    for i, row in enumerate(grid):
      for j, v in enumerate(row):
        if v:
          ans += 2 + v * 4
          if i:
            ans -= min(v, grid[i - 1][j]) * 2
          if j:
            ans -= min(v, grid[i][j - 1]) * 2
    return ans
class Solution {
  public int surfaceArea(int[][] grid) {
    int n = grid.length;
    int ans = 0;
    for (int i = 0; i < n; ++i) {
      for (int j = 0; j < n; ++j) {
        if (grid[i][j] > 0) {
          ans += 2 + grid[i][j] * 4;
          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 {
public:
  int surfaceArea(vector<vector<int>>& grid) {
    int n = grid.size();
    int ans = 0;
    for (int i = 0; i < n; ++i) {
      for (int j = 0; j < n; ++j) {
        if (grid[i][j]) {
          ans += 2 + grid[i][j] * 4;
          if (i) ans -= min(grid[i][j], grid[i - 1][j]) * 2;
          if (j) ans -= min(grid[i][j], grid[i][j - 1]) * 2;
        }
      }
    }
    return ans;
  }
};
func surfaceArea(grid [][]int) int {
  ans := 0
  for i, row := range grid {
    for j, v := range row {
      if v > 0 {
        ans += 2 + v*4
        if i > 0 {
          ans -= min(v, grid[i-1][j]) * 2
        }
        if j > 0 {
          ans -= min(v, grid[i][j-1]) * 2
        }
      }
    }
  }
  return ans
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文