카테고리 없음

[프로그래머스] 카펫 (Java, Python)

garamdev 2026. 9. 3.
728x90

문제

https://school.programmers.co.kr/learn/courses/30/lessons/42842

 

프로그래머스

SW개발자를 위한 평가, 교육의 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프

programmers.co.kr

 

코드(Java)

class Solution {
    public int[] solution(int brown, int yellow) {
        int total = brown + yellow; // 전체 격자 수 (면적)
        
        // 세로(height)는 테두리가 감싸야 하므로 최소 3 이상입니다.
        // 세로틑 최대 전체 면적의 제곱근(Math.sqrt)까지만 확인하면 됩니다.
        for (int height = 3; height <= Math.sqrt(total); height++) {
            
            // 전체 면적이 세로 길이로 나누어 떨어지는 경우만 가로(width) 후보가 됩니다.
            if (total % height == 0) {
                int width = total / height;
                
                // 노락색 카펫의 크기 조건: (가로 - 2) * (세로 - 2) == yellow
                if ((width - 2) * (height - 2) == yellow) {
                    return new int[] {width, height};
                }
            }
        }
        
        return new int[] {};
    }
}

 

코드(Python)

import math

def solution(brown, yellow):
    total = brown + yellow  # 전체 격자 수 (면적)
    
    # 세로(height)는 최소 3부터 전체 면적의 제곱근까지만 탐색
    for height in range(3, int(math.isqrt(total)) + 1):
        
        # 나누어 떨어지면 가로(width)를 계산
        if total % height == 0:
            width = total // height
            
            # 노란색 타일 조건 건증 : (가로 - 2) * (세로 - 2) == yellow
            if (width - 2) *  (height - 2) == yellow:
                return [width, height]  # [가로, 세로] 반환
    return answer