LeetCode之Projection Area of 3D Shapes(Kotlin)

問題:
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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章