[프로그래머스] LV2. 거리두기 확인하기

인스·2025년 7월 8일

💡 풀이

  • place 배열 돌면서 응시자(P) 확인 후 List에 넣기, 2차원 배열에 응시자, 테이블, 파티션 정보 넣기
  • 응시자 리스트에 2중 for문으로 두명씩 확인하기 => isCheck
  • 두 응시자의 맨해튼 거리가 1이면 무조건 false
    2이면 두 응시자 거리가 직선인 경우, 대각선인 경우 생각해서 테이블(X)이 있는지 확인하기 => checkPartition
import java.util.*;

class Solution {
    public int[] solution(String[][] places) {
        int[] answer = new int[5];
        int idx = 0;
        for(String[] place : places){
            ArrayList<int[]> pList = new ArrayList<>(); // 응시자 좌표 담기
            String[][] arr = new String[5][5];   // place 2차원 배열에 담기
            
            for(int i = 0; i<place.length; i++){
                String p = place[i];
                for(int j = 0; j<p.length(); j++){
                    if (p.charAt(j) == 'P') pList.add(new int[]{i, j});
                    arr[i][j] = String.valueOf(p.charAt(j));
                }
            }
            
            // isCheck 함수로 거리두기 확인하기
            answer[idx++] = isCheck(pList, arr) ? 1 : 0;
        }
        return answer;
    }
    
    
    public boolean isCheck(ArrayList<int[]> pList, String[][] arr){
        for(int i = 0; i<pList.size(); i++){
            for(int j = i + 1; j<pList.size(); j++){
                // 거리두기를 하라도 안지킨 응시자가 있으면 false 후 종료
                if (!checkPartition(pList.get(i), pList.get(j), arr)) {
                    return false;
                }
            }
        }
        
        return true;
    }
    
    // 거리두기 확인
    public boolean checkPartition(int[] a, int[] b, String[][] arr){
        int x1 = a[0], y1 = a[1];
        int x2 = b[0], y2 = b[1];
        
        int dist = Math.abs(x1 - x2) + Math.abs(y1 - y2);
        
        // 거리가 1인 경우
        if (dist == 1) return false;
        
        // 거리가 2인 경우
        if (dist == 2) {
            // 두 응시자 거리가 직선인 경우
            if (x1 == x2) return arr[x1][(y1 + y2) / 2].equals("X");
            else if (y1 == y2) return arr[(x1 + x2) / 2][y2].equals("X");
            // 대각선인 경우
            else return arr[x2][y1].equals("X") && arr[x1][y2].equals("X");
        } 
        
        return true;
    }
}

🫥 처음에는 무조건 조합 알고리즘 써서 2명씩 뽑고 확인하려고 했는데 그냥 2명만 뽑으면 되니까 이중 for문으로 간단하게 해도 됐다 ..!

profile
💻💡👻

0개의 댓글