883.三维形体投影面积

126 阅读1分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路。

题目

883.三维形体投影面积

题目大意

n x n 的网格 grid 中,我们放置了一些与 x,y,z 三轴对齐的 1 x 1 x 1 立方体。

每个值 v = grid[i][j] 表示 v 个正方体叠放在单元格 (i, j) 上。

现在,我们查看这些立方体在 xyyzzx 平面上的投影

投影 就像影子,将 三维 形体映射到一个 二维 平面上。从顶部、前面和侧面看立方体时,我们会看到“影子”。

返回 所有三个投影的总面积

样例

示例 1:

img

输入:[[1,2],[3,4]]
输出:17
解释:这里有该形体在三个轴对齐平面上的三个投影(“阴影部分”)。

示例 2:

输入:grid = [[2]]
输出:5

示例 3:

输入:[[1,0],[0,2]]
输出:8

数据规模

提示:

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

思路

根据题意,x\texttt{x}轴对应行,y\texttt{y} 轴对应列,z\texttt{z} 轴对应网格的数值。

因此:

  • xy\texttt{xy}平面的投影面积=网格上非零数值的数目;
  • yz\texttt{yz}平面的投影面积=网格上每一列最大数值之和;
  • zx\texttt{zx}平面的投影面积=网格上每一行最大数值之和。

分别遍历统计非零数量以及行最大值、列最大值即可。

// short int long float double bool char string void
// array vector stack queue auto const operator
// class public private static friend extern 
// sizeof new delete return cout cin memset malloc
// relloc size length memset malloc relloc size length
// for while if else switch case continue break system
// endl reverse sort swap substr begin end iterator
// namespace include define NULL nullptr exit equals 
// index col row arr err left right ans res vec que sta
// state flag ch str max min default charray std
// maxn minn INT_MAX INT_MIN push_back insert
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int, int>PII;
typedef pair<int, string>PIS;
const int maxn=1e6+50;//注意修改大小
long long read(){long long x=0,f=1;char c=getchar();while(!isdigit(c)){if(c=='-') f=-1;c=getchar();}while(isdigit(c)){x=x*10+c-'0';c=getchar();}return x*f;}
ll qpow(ll x,ll q,ll Mod){ll ans=1;while(q){if(q&1)ans=ans*x%Mod;q>>=1;x=(x*x)%Mod;}return ans%Mod;}

class Solution {
public:
    int projectionArea(vector<vector<int>>& grid) {
        int ans=0,n=grid.size(),m=grid[0].size();
        for(auto a:grid){
            for(auto v:a){
                ans+=(v!=0);
            }
        }
        for(auto a:grid){
            int maxx=0;
            for(auto v:a){
                maxx=max(maxx,v);
            }
            ans+=maxx;
        }
        for(int j=0;j<m;j++){
            int maxx=0;
            for(int i=0;i<n;i++){
                maxx=max(maxx,grid[i][j]);
            }
            ans+=maxx;
        }
        return ans;
    }
};