On a N * N grid, we place some 1 * 1 * 1cubes.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

需要注意的是,这个不是投影,而是surface,只要没有和其他相邻的表面都算surface

class Solution {
    public int surfaceArea(int[][] grid) {
        int res = 0;
        int n = grid.length;

        for(int i = 0; i < n; i++) {
            for(int j = 0; j < n; j++) {
                if(grid[i][j] != 0)
                    res += getSurfaceArea(grid, i, j);
            }
        }

        return res;
    }

    public int getSurfaceArea(int[][] grid, int i, int j) {
        int n = grid.length;
        int res = 2;

        if(i - 1 < 0)
            res += grid[i][j];
        else if(grid[i - 1][j] < grid[i][j])
            res += grid[i][j] - grid[i - 1][j];

        if(i + 1 == n)
            res += grid[i][j];
        else if(grid[i + 1][j] < grid[i][j])
            res += grid[i][j] - grid[i + 1][j];

        if(j - 1 < 0)
            res += grid[i][j];
        else if(grid[i][j - 1] < grid[i][j])
            res += grid[i][j] - grid[i][j - 1];

        if(j + 1 == n)
            res += grid[i][j];
        else if(grid[i][j + 1] < grid[i][j])
            res += grid[i][j] - grid[i][j + 1];

        return res;
    }
}

results matching ""

    No results matching ""