[LeetCode] 883. Projection Area of 3D Shapes 三維物體的投影面積



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: [[2]]
Output: 5

Example 2:

Input: [[1,2],[3,4]]
Output: 17
Explanation:
Here are the three projections ("shadows") of the shape made with each axis-aligned plane.


Example 3:

Input: [[1,0],[0,2]]
Output: 8

Example 4:

Input: [[1,1,1],[1,0,1],[1,1,1]]
Output: 14

Example 5:

Input: [[2,2,2],[2,1,2],[2,2,2]]
Output: 21

Note:

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

這道題給了我們一個二維數組 grid,用來表示一個 3D 物體形狀,表示方法是 grid[i][j] 表示在 (i, j) 位置上的高度,就像壘積木一樣,累出了一個三維物體。然后讓我們計算三個方向的投影面積之和,所謂的三個方向分別是上方 Top,前方 Front,和側方 Side。用過一些三維建模軟件(例如 Maya, 3DMax)的同學,對這個應該不陌生。我們先來考慮正上方投影面積如何計算,由於題目中說了 grid 數組的寬和高相等,那么上方投影就是一個正方形,前提是每個 grid[i][j] 的值都大於0的話。因為若 grid 數組中有0存在,則表示正方形投影會缺少了一塊。由於這個大的正方形投影是由 nxn 個小的正方形組成,那么實際上我們只要統計出小正方形的個數,那么大正方形投影的面積也就知道了(是不有點微積分的感覺)。所以我們在遍歷的過程中,只要判斷若 grid[i][j] 大於0,則結果 res 自增1即可。下面再來考慮另外兩個方向的投影怎么計算,另兩個方向的投影的可能是不規則圖形,參見題目中給的那個圖,如果仔細觀察的話,其投影圖像的每個階段的高其實就是各行或各列中的最大值,這也不難理解,就像城市中聳立的高度不同的大樓,若要描出城市的輪廓,那么描出來的肯定都是每個位置上最高建築物的輪廓。那么問題就變成了累加各行各列的最大值。我們實際上在一次遍歷中就能完成,使用了一個小 trick,那就是在第二層 for 循環中,行最大值 rowMax 就是不斷用 grid[i][j] 來更新,而列最大值 colMax 就是不斷用 grid[j][i] 來更新,巧妙的交換i和j,實現了目標。然后分別把更新出來的行列最大值加到結果 res 中即可,參見代碼如下:
class Solution {
public:
    int projectionArea(vector<vector<int>>& grid) {
		int n = grid[0].size(), res = 0;
		for (int i = 0; i < n; ++i) {
			int rowMax = 0, colMax = 0;
			for (int j = 0; j < n; ++j) {
                if (grid[i][j] > 0) ++res;
				rowMax = max(rowMax, grid[i][j]);
				colMax = max(colMax, grid[j][i]);
			}
			res += rowMax + colMax;
		}
		return res;
    }
};

Github 同步地址:

https://github.com/grandyang/leetcode/issues/883


參考資料:

https://leetcode.com/problems/projection-area-of-3d-shapes/

https://leetcode.com/problems/projection-area-of-3d-shapes/discuss/156726/C%2B%2BJavaPython-Straight-Forward

https://leetcode.com/problems/projection-area-of-3d-shapes/discuss/156771/11-line-1-pass-Java-code-and-explanation-of-the-problem-time-O(N-2)-space-O(1).


[LeetCode All in One 題目講解匯總(持續更新中...)](https://www.cnblogs.com/grandyang/p/4606334.html)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM