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
// OJ: https://leetcode.com/problems/surface-area-of-3d-shapes/
// Author: github.com/lzl124631x
// Time: O(N^2)
// Space: O(1)
class Solution {
public:
int surfaceArea(vector<vector<int>>& grid) {
int N = grid.size(), area = 0;
for (int i = 0; i < N; ++i) {
int prev = 0;
for (int j = 0; j < N; ++j) {
if (grid[i][j]) area += 2;
area += abs(grid[i][j] - prev);
prev = grid[i][j];
}
area += prev;
}
for (int i = 0; i < N; ++i) {
int prev = 0;
for (int j = 0; j < N; ++j) {
area += abs(grid[j][i] - prev);
prev = grid[j][i];
}
area += prev;
}
return area;
}
};
// OJ: https://leetcode.com/problems/surface-area-of-3d-shapes/
// Author: github.com/lzl124631x
// Time: O(N^2)
// Space: O(1)
class Solution {
private:
int dirs[4][2] = {{0,1}, {-1,0}, {0,-1}, {1,0}};
public:
int surfaceArea(vector<vector<int>>& grid) {
int N = grid.size(), area = 0;
for (int i = 0; i < N; ++i) {
for (int j = 0; j < N; ++j) {
if (!grid[i][j]) continue;
area += 2;
for (auto &dir : dirs) {
int x = i + dir[0], y = j + dir[1];
int h = x < 0 || x >= N || y < 0 || y >= N ? 0 : grid[x][y];
area += max(grid[i][j] - h, 0);
}
}
}
return area;
}
};