classSolution { publicintsurfaceArea(int[][] grid) { int[] dr = newint[]{0, 1, 0, -1}; int[] dc = newint[]{1, 0, -1, 0};
intN= grid.length; intans=0;
for (intr=0; r < N; ++r) { for (intc=0; c < N; ++c) { if (grid[r][c] > 0) { ans += 2; for (intk=0; k < 4; ++k) { intnr= r + dr[k]; intnc= c + dc[k]; intnv=0; if (0 <= nr && nr < N && 0 <= nc && nc < N) { nv = grid[nr][nc]; }
ans += Math.max(grid[r][c] - nv, 0); } } } }
return ans; } }
[sol1-Python3]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
classSolution: defsurfaceArea(self, grid: List[List[int]]) -> int: N = len(grid)
ans = 0 for r inrange(N): for c inrange(N): if grid[r][c]: ans += 2 for nr, nc in ((r - 1, c), (r + 1, c), (r, c - 1), (r, c + 1)): if0 <= nr < N and0 <= nc < N: nval = grid[nr][nc] else: nval = 0
classSolution { public: intsurfaceArea(vector<vector<int>>& grid){ int dr[]{0, 1, 0, -1}; int dc[]{1, 0, -1, 0};
int N = grid.size(); int ans = 0;
for (int r = 0; r < N; ++r) { for (int c = 0; c < N; ++c) { if (grid[r][c] > 0) { ans += 2; for (int k = 0; k < 4; ++k) { int nr = r + dr[k]; int nc = c + dc[k]; int nv = 0; if (0 <= nr && nr < N && 0 <= nc && nc < N) { nv = grid[nr][nc]; }
var surfaceArea = function(grid) { const dr = [0, 1, 0, -1]; const dc = [1, 0, -1, 0];
const N = grid.length; let ans = 0;
for (let r = 0; r < N; ++r) { for (let c = 0; c < N; ++c) { if (grid[r][c] > 0) { ans += 2; for (let k = 0; k < 4; ++k) { const nr = r + dr[k]; const nc = c + dc[k]; let nv = 0; if (0 <= nr && nr < N && 0 <= nc && nc < N) { nv = grid[nr][nc]; }