LeetCode 题解工作台

三维形体的表面积

给你一个 n * n 的网格 grid ,上面放置着一些 1 x 1 x 1 的正方体。每个值 v = grid[i][j] 表示 v 个正方体叠放在对应单元格 (i, j) 上。 放置好正方体后,任何直接相邻的正方体都会互相粘在一起,形成一些不规则的三维形体。 请你返回最终这些形体的总表面积。 注…

category

4

题型

code_blocks

4

代码语言

hub

3

相关题

当前训练重点

简单 · 数组·数学

bolt

答案摘要

时间复杂度 ,空间复杂度 。 class Solution:

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数组·数学 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个 n * n 的网格 grid ,上面放置着一些 1 x 1 x 1 的正方体。每个值 v = grid[i][j] 表示 v 个正方体叠放在对应单元格 (i, j) 上。

放置好正方体后,任何直接相邻的正方体都会互相粘在一起,形成一些不规则的三维形体。

请你返回最终这些形体的总表面积。

注意:每个形体的底面也需要计入表面积中。

 

示例 1:

输入:grid = [[1,2],[3,4]]
输出:34

示例 2:

输入:grid = [[1,1,1],[1,0,1],[1,1,1]]
输出:32

示例 3:

输入:grid = [[2,2,2],[2,1,2],[2,2,2]]
输出:46

 

提示:

  • n == grid.length
  • n == grid[i].length
  • 1 <= n <= 50
  • 0 <= grid[i][j] <= 50
lightbulb

解题思路

方法一:遍历,逐个累加

时间复杂度 O(n2)O(n^2),空间复杂度 O(1)O(1)

1
2
3
4
5
6
7
8
9
10
11
12
13
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
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Look for understanding of how adjacency affects surface area calculations.

  • question_mark

    Evaluate if the candidate considers optimizations for repeated calculations.

  • question_mark

    Check if the solution correctly handles edge cases like adjacent towers of equal or differing heights.

warning

常见陷阱

外企场景
  • error

    Failing to account for hidden sides between adjacent cubes.

  • error

    Overcomplicating the solution when a direct traversal of the grid is sufficient.

  • error

    Not handling edge cases like empty or minimal grids (e.g., n = 1 or towers with height 0).

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Consider cases where some cells contain zero cubes.

  • arrow_right_alt

    What happens when the grid contains large numbers or is very sparse?

  • arrow_right_alt

    Can this problem be generalized to irregular 3D shapes?

help

常见问题

外企场景

三维形体的表面积题解:数组·数学 | LeetCode #892 简单