[Hacker Rank] 3D Surface Area

3D Surface Area

  • Time : O(nm)
  • Space : O(1)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
int surfaceArea(vector<vector<int>> A) {
int res = 0, n = A.size(), m = A[0].size();
int dy[4]{-1,0,1,0},dx[4]{0,1,0,-1};
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
res += 2 + 4 * A[i][j];
for(int k = 0; k < 4; k++) {
int ny = i + dy[k], nx = j + dx[k];
if(0 <= ny and ny < n and 0 <= nx and nx < m) {
res -= min(A[i][j], A[ny][nx]);
}
}
}
}
return res;
}
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/06/10/PS/HackerRank/3d-surface-area/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.