코린이의 소소한 공부노트

[LeetCode/Easy] 892. Surface Area of 3D Shapes 본문

코딩테스트 풀이/JAVA

[LeetCode/Easy] 892. Surface Area of 3D Shapes

무지맘 2023. 5. 31. 15:58

1. Input

1) int[][] grid

- grid[i][j] == (i,j)에 쌓여있는 1*1*1 큐브의 개수

 

2. Output

1) grid를 이루고 있는 입체도형의 겉넓이를 반환

- 밑면도 겉넓이에 포함된다.

 

3. Constraint

1) n == grid.length == grid[i].length

2) 1 <= n <= 50

3) 0 <= grid[i][j] <= 50

 

4. Example

Input: grid = [[1,2],[3,4]] -> Output: 34

Input: grid = [[1,1,1],[1,0,1],[1,1,1]] -> Output: 32

 

5. Code

1) 첫 코드(2023/05/31)

class Solution {
    public int surfaceArea(int[][] grid) {
        int answer = 0, n = grid.length;
        for(int i=0 ; i<n ; i++){
            for(int j=0 ; j<n ; j++){
                answer += grid[i][j]==0 ? 0 : grid[i][j]*4+2;
                if(i<n-1)
                    answer -= Math.min(grid[i][j], grid[i+1][j])*2;
                if(j<n-1)
                    answer -= Math.min(grid[i][j], grid[i][j+1])*2;
            }
        }
        return answer;
    }
}

- 94%, 6%