-
Notifications
You must be signed in to change notification settings - Fork 0
/
Surface Area of 3D Shapes
69 lines (63 loc) · 2.28 KB
/
Surface Area of 3D Shapes
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
66
67
68
69
Surface Area of 3D Shapes
You are given an n x n grid where you have placed some 1 x 1 x 1 cubes. Each value v = grid[i][j] represents a tower of v cubes placed on top of cell (i, j).
After placing these cubes, you have decided to glue any directly adjacent cubes to each other, forming several irregular 3D shapes.
Return the total surface area of the resulting shapes.
Note: The bottom face of each shape counts toward its surface area.
Example 1:
Input: grid = [[1,2],[3,4]]
Output: 34
Example 2:
Input: grid = [[1,1,1],[1,0,1],[1,1,1]]
Output: 32
Example 3:
Input: grid = [[2,2,2],[2,1,2],[2,2,2]]
Output: 46
class Solution {
public int surfaceArea(int[][] grid) {
int sum = 0;
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[0].length; j++) {
int h = grid[i][j];
int fullS = h > 0 ? h * 4 + 2 : 0;
//check adjacent and substract touching surface
//check left
if (cellExists(i, j - 1, grid)) {
if (h <= grid[i][j - 1]) {
fullS -= h;
} else {
fullS -= grid[i][j - 1];
}
}
//check up
if (cellExists(i - 1, j, grid)) {
if (h <= grid[i - 1][j]) {
fullS -= h;
} else {
fullS -= grid[i - 1][j];
}
}
//check right
if (cellExists(i, j + 1, grid)) {
if (h <= grid[i][j + 1]) {
fullS -= h;
} else {
fullS -= grid[i][j + 1];
}
}
//check down
if (cellExists(i + 1, j, grid)) {
if (h <= grid[i + 1][j]) {
fullS -= h;
} else {
fullS -= grid[i + 1][j];
}
}
sum += fullS;
}
}
return sum;
}
private static boolean cellExists(int row, int col, int[][] array) {
return (row <= array.length - 1 && row >= 0) && (col <= array[0].length - 1 && col >= 0);
}
}