본문 바로가기
PS 문제 풀이/HackerRank

[HackerRank] 3D Surface Area

by 까망 하르방 2021. 2. 18.
반응형

출처: https://www.hackerrank.com/challenges/3d-surface-area/problem

 Input 

3 3

1 3 4

2 2 3

1 2 4

  

 Output 

60 

윗면, 아랫면 각 Cube의 높낮이와 상관없이 h * w * 2이다.

그렇기에 옆면의 높이를 비교해서 총 면적을 구한다.


import java.util.Arrays;
import java.util.Scanner;
 
public class Solution {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
         
        int h = sc.nextInt();
        int w = sc.nextInt();
        int[][] cube = new int[h][w];
         
        for(int i=0; i<h; i++) {
            for(int j=0; j<w; j++) {
                cube[i][j] = sc.nextInt();
            }
        }
         
        // 기본적으로 높이에 상관없이 윗면과 아랫면 각각의 높이랑은 상관 없다.
        int surface = (h * w) * 2;
         
        int[] dirX = {-1,1,0,0};
        int[] dirY = {0,0,-1,1};
         
        // 윗, 아랫면은 고려치 않고 상하좌우만 고려한다.
        for(int x=0; x<h; x++) {
            for(int y=0; y<w; y++) {
                 
                for(int d=0; d<4; d++) {
                    int cx = x + dirX[d];
                    int cy = y + dirY[d];
                     
                    if(cx < 0 || cx >= h || cy < 0 || cy >= w) {
                        surface = surface + cube[x][y]; // 높이 그대로 축적
                    }else { // 해당 방향에 Cube가 존재하므로 높이를 비교해야 한다.
                        // 현재 큐브가 비교되는 큐브보다 높다면 차이만큼 축적
                        // 큐브 높이가 낮은 경우에는 해당 면이 덮여있으므로 skip
                        if(cube[x][y] > cube[cx][cy]) {
                            surface = surface + Math.abs(cube[x][y]-cube[cx][cy]);
                        }
                    }
                }
            }
        }
         
        System.out.println(surface);
    }
}

 

반응형

'PS 문제 풀이 > HackerRank' 카테고리의 다른 글

[HackerRank] Strange Counter  (0) 2021.02.18
[HackerRank] Cavity Map  (0) 2021.02.18
[HackerRank] Repeated String (Java)  (0) 2021.02.14
[HackerRank] Almost Sorted (Java)  (0) 2021.02.14
[HackerRank] Cut the sticks (Java)  (0) 2021.02.14

댓글