883. Projection Area of 3D Shapes(python+cpp)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_21275321/article/details/82743919

题目:

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

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

解释:
用一个函数判断是否是self-dividing。

python代码:

class Solution(object):
    def projectionArea(self, grid):
        """
        :type grid: List[List[int]]
        :rtype: int
        """
        aera_1,aera_2,aera_3=0,0,0
        N=len(grid)
        for i in range(N):
            tmp=[]
            aera_2+=max(grid[i])
            for j in range(N):
                if grid[i][j]:
                    aera_1+=1
                tmp.append(grid[j][i])
            aera_3+=max(tmp)
        return aera_1+aera_2+aera_3

c++代码:

扫描二维码关注公众号,回复: 3504798 查看本文章
class Solution {
public:
    int projectionArea(vector<vector<int>>& grid) {
        int area_1=0,area_2=0,area_3=0;
        int N=grid.size();
        for(int i=0;i<N;i++)
        {
            area_1+=*(max_element(grid[i].begin(),grid[i].end()));
            vector<int>tmp;
            for (int j=0;j<N;j++)
            {
                if (grid[i][j])
                    area_2+=1;
                tmp.push_back(grid[j][i]);
                
            }
            area_3+=*(max_element(tmp.begin(),tmp.end()));
        }
        return area_1+area_2+area_3;
        
    }
};

总结:
学会使用 max_element()函数,注意 max_element()函数返回的是指针,要求最大值时需要*,cpp的值一定要初始化,不然是随机值而不是0,这个一定要注意哟~

猜你喜欢

转载自blog.csdn.net/qq_21275321/article/details/82743919
今日推荐