[892] The three-dimensional body surface area

892. The three-dimensional body surface area


link

Title Description

Here Insert Picture Description

Thinking

All calculated 正方体的总个数, the total surface area that 6 * 总个数
each have a surface coincident, the surface area will be reduced 2
again to find mating plane:

  • Present on the same number of lattice> cube of 2, the number of overlapping surfaces = --1
  • Left and right polymerization
  • The upper and lower polymerization
class Solution {
    public int surfaceArea(int[][] grid) {
        if(grid == null || grid.length == 0){
            return 0;
        }
        int coincide = 0;
        int sumNum = 0;
        for(int i = 0 ; i < grid.length ;i++){
            for(int j = 0; j < grid[0].length ; j++){
            	//左右重合
                if(j < grid[0].length-1){
                    coincide += Math.min(grid[i][j],grid[i][j+1]);
                }
                //上下重合
                if(i < grid.length-1 ){
                    coincide += Math.min(grid[i][j],grid[i+1][j]);
                }
                //同一个格子上重合
                if(grid[i][j] > 1){
                    coincide += grid[i][j]-1;
                }
                sumNum += grid[i][j];
            }
        }
        return 6*sumNum - 2*coincide;
    }
}

More concise wording, use bit computing

For each cylinder in terms of: a surface area of both upper and lower surfaces and four side surfaces of each cube
subtracting the overlap can be

class Solution {
    public int surfaceArea(int[][] grid) {
        if(grid == null || grid.length == 0){
            return 0;
        }
        int n = grid.length;
        int area = 0;
        for(int i = 0; i < n;i++){
            for(int j = 0; j < n;j++){
                int level = grid[i][j];
                if(level > 0){
                    area += (level << 2) + 2;
                    area -= i > 0 ? ((Math.min(level,grid[i-1][j])) << 1) : 0;
                    area -= j > 0 ? ((Math.min(level,grid[i][j-1])) << 1) : 0;
                }
            }
        }
        return area;
    }
}
Published 55 original articles · won praise 1 · views 863

Guess you like

Origin blog.csdn.net/weixin_42469108/article/details/105112192