问题: 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.git
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轴方向上最大元素的和,最后把三个方向的数目加总即为结果。github
具体实现:bash
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))
}
复制代码
有问题随时沟通ide