알고리즘/프로그래머스

거리두기 확인하기

베리영young 2024. 12. 2. 02:21

사용 알고리즘: 구현

사용 언어: java

 

import java.util.*;
//P사람 O테이블 X파티션
//지키면 1, 아니면 0

class Solution {
    int len;
    //1거리 이내인 것 찾기:4방(의심의 여지없이 나가리)
    int[] dx_1 = {0,-1,0,1};
    int[] dy_1 = {-1,0,1,0};
    //2거리 이내인 것: 파티션으로 회생 가능(2*4방)
    int[] dx_2_1 = {0,-2,0,2};
    int[] dy_2_1 = {-2,0,2,0};
    //대각
    int[] dx_2_2 = {-1,-1,1,1};
    int[] dy_2_2 = {-1,1,1,-1};
    
    public int[] solution(String[][] places) {
        len = places.length;
        
        int[] answer = new int[len];
        for(int i=0; i<len; i++) {
            answer[i] = rooms(places[i]);
        }
        
        return answer;
    }
    
    public int rooms(String[] place) {
        //P위치 찾기
        for(int i=0; i<5; i++) {
            for(int j=0; j<5; j++) {
                if(place[i].charAt(j) == 'P') {
                    //1거리 이내가 하나라도 있으면 0
                    if(!notIn1dis(place, i,j)) return 0;
                    //2거리 이내(가로세로)인데, 파티션x면 0
                    if(!notIn2dis_1(place, i,j)) return 0;
                    //2거리 이내(대각선)인데, 파티션x면 0
                    if(!notIn2dis_2(place, i,j)) return 0;
                }
            }
        }
        return 1;
    }
    
    public boolean notIn2dis_2(String[] place, int x,int y) {
        for(int d=0; d<4; d++) {
            int nx = x + dx_2_2[d];
            int ny = y + dy_2_2[d];
            
            if(nx<0||nx>=5 || ny<0||ny>=5) continue;
            if(place[nx].charAt(ny) == 'P' && (
               place[x+dx_1[d]].charAt(y + dy_1[d]) == 'O' || 
               place[x+dx_1[(d+1)%4]].charAt(y + dy_1[(d+1)%4]) == 'O')) return false;
        }
        return true;
    }
    
    public boolean notIn2dis_1(String[] place, int x,int y) {
        for(int d=0; d<4; d++) {
            int nx = x + dx_2_1[d];
            int ny = y + dy_2_1[d];
            
            if(nx<0||nx>=5 || ny<0||ny>=5) continue;
            if(place[nx].charAt(ny) == 'P' 
               && place[x+dx_1[d]].charAt(y + dy_1[d]) != 'X') return false;
        }
        return true;
    }
    
    public boolean notIn1dis(String[] place, int x,int y) {
        for(int d=0; d<4; d++) {
            int nx = x + dx_1[d];
            int ny = y + dy_1[d];
            
            if(nx<0||nx>=5 || ny<0||ny>=5) continue;
            
            if(place[nx].charAt(ny) == 'P') return false;
        }
        return true;
    }
}

 

어려울 건 없는 그냥 구현