• + 24 comments

    Store the height of each 'pillar' in a 1-based 2d array. Fill row 0, col 0, row H+1, col W+1 with dummy 0 (to ease calculation and avoid if statements). Then, we just need to calculate the SUM of 'visible' side-area of each pillar by subtracting that side-height with its adjacent side-height, if it is a positive value, then it is visible then add it to the SUM, else if it is a negative value, it is not visible and don't add it to the SUM. Lastly, add the top and bottom surface area (2*W*H) to the SUM.

    static int surfaceArea(int[][] A) {
        int area = 2*W*H;
        for (int i = 1; i <= H; i++) {
            for (int j = 1; j <= W; j++) {
                area += Math.max(0, A[i][j]-A[i-1][j]);
                area += Math.max(0, A[i][j]-A[i+1][j]);
                area += Math.max(0, A[i][j]-A[i][j-1]);
                area += Math.max(0, A[i][j]-A[i][j+1]);
            }
        }
        return area;
    }
    

    sorry for my bad english and poor explanation.