LeetCode之Projection Area of 3D Shapes(Kotlin)

本文介绍了一种计算三维形状在xy、yz和zx平面上投影面积的算法。通过统计非零元素、y轴方向最大元素之和及x轴方向最大元素之和,实现了三维网格上放置立方体的投影总面积计算。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

问题:
On a N * N grid, we place some 1 * 1 * 1 cubes that are axis-aligned with the x, y, and z axes.
Each value v = grid[i][j] represents a tower of v cubes placed on top of grid cell (i, j).
Now we view the projection of these cubes onto the xy, yz, and zx planes.
A projection is like a shadow, that maps our 3 dimensional figure to a 2 dimensional plane.
Here, we are viewing the “shadow” when looking at the cubes from the top, the front, and the side.
Return the total area of all three projections.

Example 1:

Input: [[1,2],[3,4]]
Output: 17

Note:

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

方法:
top方向的数目等于矩阵中所有非零元素的个数,left方向的数目等于y轴方向上最大元素的和,front方向的数目等于x轴方向上最大元素的和,最后把三个方向的数目加总即为结果。

具体实现:

class ProjectionAreaOf3DShapes {
    fun projectionArea(grid: Array<IntArray>): Int {
        var top = 0
        var left = 0
        var front = 0

        grid.indices.forEach { i ->
            grid[0].indices.forEach { j ->
                if (grid[i][j] > 0) {
                    top++
                }
            }
        }

        var yMax = 0
        grid.indices.forEach { i ->
            grid[0].indices.forEach { j ->
                if (grid[i][j] > yMax) {
                    yMax = grid[i][j]
                }
            }
            left += yMax
            yMax = 0
        }

        var xMax = 0
        grid[0].indices.forEach { j ->
            grid.indices.forEach { i ->
                if (grid[i][j] > xMax) {
                    xMax = grid[i][j]
                }
            }
            front += xMax
            xMax = 0
        }
        return top + left + front
    }
}

fun main(args: Array<String>) {
    val input = arrayOf(intArrayOf(1, 0), intArrayOf(0, 2))
    val projectionAreaOf3DShapes = ProjectionAreaOf3DShapes()
    println(projectionAreaOf3DShapes.projectionArea(input))
}

有问题随时沟通

具体代码实现可以参考Github

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值