LC 892. Surface Area of 3D Shapes

Nilanjan Deb · April 6, 2020

This is my CPP solution.

class Solution {
public:
    int surfaceArea(vector<vector<int>>& grid) {
        int len = grid.size(), surfaceArea = 0;
        for(int j=0;j<len;j++)
            surfaceArea=surfaceArea+grid[0][j];
        for(int j=0;j<len;j++)
            surfaceArea=surfaceArea+grid[len-1][j];
        for(int i=0;i<len;i++)
            surfaceArea=surfaceArea+grid[i][0];
        for(int i=0;i<len;i++)
            surfaceArea=surfaceArea+grid[i][len-1];
        surfaceArea = surfaceArea + 2*(len*len);
        for(int i=0;i<len;i++)
            for(int j=0;j<len;j++)
                if(grid[i][j] == 0)
                    surfaceArea-=(2*1);
        for(int i=0;i<len;i++)
            for(int j=1;j<len;j++)
                surfaceArea = surfaceArea + abs(grid[i][j]-grid[i][j-1]);
        for(int j=0;j<len;j++)
            for(int i=1;i<len;i++)
                surfaceArea = surfaceArea + abs(grid[i][j]-grid[i-1][j]);
        return surfaceArea;
    }
};


Dicussion Forum