892. Surface Area of 3D Shapes
https://leetcode.com/problems/surface-area-of-3d-shapes/
js
/**
* @param {number[][]} grid
* @return {number}
*/
var surfaceArea = function(grid) {
let surface = 0
let rows = grid.length
let cols = grid[0].length
for (let i = 0; i < rows; i++) {
for (let j = 0; j < cols; j++) {
let c = grid[i][j]
if (c === 0) {
continue
}
let front = i == rows - 1 ? c : Math.max(0, c - grid[i + 1][j])
let back = i === 0 ? c : Math.max(0, c - grid[i - 1][j])
let left = j === 0 ? c : Math.max(0, c - grid[i][j - 1])
let right = j === cols - 1 ? c : Math.max(0, c - grid[i][j + 1])
surface = surface + front + back + left + right + 2
}
}
return surface
}
py
class Solution:
def surfaceArea(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
rows = len(grid)
cols = len(grid[0])
surface = 0
for i in range(rows):
for j in range(cols):
c = grid[i][j]
if c == 0:
continue
front = c if i == rows - 1 else max(0, c - grid[i + 1][j])
back = c if i == 0 else max(0, c - grid[i - 1][j])
left = c if j == 0 else max(0, c - grid[i][j - 1])
right = c if j == cols - 1 else max(0, c - grid[i][j + 1])
surface = surface + front + back + left + right + 2
return surface