892. The three-dimensional body surface area per day double hundred Golang a problem

892. The three-dimensional body surface area

N * N on the grid, we put some cube 1 * 1 * 1.

Each value v = grid [i] [j] denotes the v cube superposed on the corresponding cell (i, j).

Please return to the final body surface area.

Example 1:

Input: [[2]]
Output: 10

Example 2:

Input: [[1,2], [3,4]]
Output: 34

Example 3:

Input: [[1,0], [0,2]]
Output: 16

Example 4:

Input: [[1,1,1], [1,0,1], [1,1,1]]
Output: 32

Example 5:

Input: [[2,2,2], [2,1,2], [2,2,2]]
Output: 46

prompt:

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

Thinking

First, to separate the cut bars for each position, each of the bins of the surface area of ​​4n + 2. And then subtracting the overlapping area between the bins, where only consider the top left, to avoid double counting. Repeat area of ​​min (n1, n2) * 2.

My answer

Here Insert Picture Description

func surfaceArea(grid [][]int) int {
	sf:=0
	for i:=0;i<len(grid);i++{
		for j:=0;j<len(grid[0]);j++{
			if grid[i][j]!=0{
				sf+=grid[i][j]*4+2
				if i>0{
					sf-=min(grid[i][j],grid[i-1][j])*2
				}
				if j>0{
					sf-=min(grid[i][j],grid[i][j-1])*2
				}
			}
		}
	}
	return sf
}
func min(x,y int) int {
	if x<y{
		return x
	}
	return y
}
Published 38 original articles · won praise 0 · Views 1018

Guess you like

Origin blog.csdn.net/Cyan1956/article/details/105087050