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