892. 三维形体的表面积(javascript)892. Surface Area of 3D Shapes

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

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

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

注意:每个形体的底面也需要计入表面积中。
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.

示例 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
  1. 对每一项进行遍历,当grid[i][j]值存在时才会有加有减

  2. grid[i][j]的表面积(没有去除左右重叠部分) 2 + 4 * grid[i][j]

  3. 只需要减掉右边和上面的 重叠部分*2(重叠部分取两个相邻的最小值)

var surfaceArea = function (grid) {
    let len = grid.length
    let sum = 0
    for (let i = 0; i < len; i++) {
        for (let j = 0; j < len; j++) {
            let v = grid[i][j]
            if (!v) {
                continue
            }
            sum += 2 + 4 * v
            if (i - 1 >= 0) {
                sum -= Math.min(grid[i][j], grid[i - 1][j]) * 2
            }
            if (j + 1 < len) {
                sum -= Math.min(grid[i][j], grid[i][j + 1]) * 2
            }
        }

    }
    return sum
};

leetcode:https://leetcode.cn/problems/surface-area-of-3d-shapes/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值