-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathsurfaceArea.go
More file actions
65 lines (48 loc) · 1.02 KB
/
Copy pathsurfaceArea.go
File metadata and controls
65 lines (48 loc) · 1.02 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
/* https://leetcode.com/problems/surface-area-of-3d-shapes/description/
On a N * N grid, we place some 1 * 1 * 1 cubes.
Each value v = grid[i][j] represents a tower of v cubes placed on top of grid cell (i, j).
Return the total surface area of the resulting shapes.
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
Note:
1 <= N <= 50
0 <= grid[i][j] <= 50
*/
package lmath
func surfaceArea(grid [][]int) int {
abs := func(a int) int {
if a < 0 {
return -a
}
return a
}
I, J := len(grid), len(grid[0])
xx, xz, xy := 0, 0, 0
for i := 0; i < I; i++ {
tmpXZ, tmpXY := 0, 0
for j := 0; j < J; j++ {
if grid[i][j] != 0 {
xx += 2 // bottom and top
}
xz += abs(grid[i][j] - tmpXZ)
xy += abs(grid[j][i] - tmpXY)
tmpXZ, tmpXY = grid[i][j], grid[j][i]
}
xz += tmpXZ
xy += tmpXY
}
return xx + xz + xy
}