892. The surface area of the three-dimensional body

Title description

On the N * N grid, we place some 1 * 1 * 1 cubes.
Each value v = grid[i][j] means v cubes are stacked on the corresponding cell (i, j).
Please return the surface area of ​​the final form.

Example

示例 1:

输入:[[2]]
输出:10

示例 2:

输入:[[1,2],[3,4]]
输出:34

示例 3:

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

示例 4:

输入:[[1,1,1],[1,0,1],[1,1,1]]
输出:32

示例 5:

输入:[[2,2,2],[2,1,2],[2,2,2]]
输出:46

prompt

1 <= N <= 50
0 <= grid[i][j] <= 50

Problem solving ideas

Calculate the total area and subtract the hidden surface area. Top
and bottom coverage, left and right coverage, front and back coverage each -2

Code

int surfaceArea(int** grid, int gridSize, int* gridColSize){
    
    
    int s=0;
    int k;
    for(int i=0;i<gridSize;i++){
    
    
        for(int j=0;j<*gridColSize;j++){
    
    
            for(k=0; k<grid[i][j]; k++){
    
    
                s+=6;//一个立方体表面积为6
                if(k>0){
    
    
                    s -= 2;
                }
                // 前面相邻
                if(i>0 && grid[i-1][j]>k){
    
    
                    s -= 2;
                }
                // 左面相邻
                if(j>0 && grid[i][j-1]>k){
    
    
                    s -= 2;
                }
            }
        }
    }
    return s; 

}

link

Guess you like

Origin blog.csdn.net/qq_44722674/article/details/112530531