参考:
https://leetcode-cn.com/problems/surface-area-of-3d-shapes/solution/san-wei-xing-ti-de-biao-mian-ji-by-leetcode/

import static java.lang.Math.min;

public class Solution {
    public int surfaceArea(int[][] grid) {
        int ret = 0;
        int length = grid.length;
        for(int i = 0;i<length;++i){
            for(int j = 0;j<grid[0].length;++j){
                if(grid[i][j]>0) {
                    ret+=4*grid[i][j]+2;
                }
                if(i<length-1) {
                    //扣除与右边重叠
                    ret-=(min(grid[i][j],grid[i+1][j])*2);
                }
                if(j<length-1) {
                    //扣除与下边重叠
                    ret-=(min(grid[i][j],grid[i][j+1])*2);
                }
            }
        }
        return ret;
    }
}
```


class Solution(object):
    def surfaceArea(self, grid):
        N = len(grid)

        ans = 0
        for r in range(N-1,-1,-1):
            for c in range(N-1,-1,-1):
                if grid[r][c]:
                    ans += 2
                    for nr, nc in ((r-1, c), (r+1, c), (r, c-1), (r,c+1)):
                        if 0 <= nr < N and 0 <= nc < N:
                            nval = grid[nr][nc]
                        else:
                            nval = 0

                        ans += max(grid[r][c] - nval, 0)

        return ans