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:
Input: [[1,2],[3,4]]
Output: 17
Explanation:
Here are the three projections ("shadows") of the shape made with each axis-aligned plane.
这道题本来就老老实实地计算3个方向的投影就可以了,直接计算需要储存每一行和每一列的投影,这样的话需要额外的空间。但是有一个可以优化的原因是题目中给定了这个矩阵是N * N的,所以行列的遍历可以同时进行。如果是更一般化的M * N的矩阵,则至少需要额外的O(M)或O(N)的空间
class Solution {
public int projectionArea(int[][] grid) {
if(grid == null || grid.length == 0 || grid[0] == null || grid[0].length == 0)
return 0;
int res = 0;
int bottom = 0;
int n = grid.length;
for(int i = 0; i < n; i++) {
int row = 0;
int col = 0;
for(int j = 0; j < n; j++) {
if(grid[i][j] != 0)
res++;
row = Math.max(row, grid[i][j]);
col = Math.max(col, grid[j][i]);
}
res += row;
res += col;
}
return res;
}
}