Coding Test/programmers

[Java, Python] 거리두기 확인하기 (2차원배열, 좌표)

Karla Ko 2024. 3. 19. 19:21
728x90

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

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

  1. 입력 가공 String  ➡️ char
  2. 거리두기 검사
    1. 모든 좌표에 대해 반복
      1. 응시자인 경우
        1. 다음 좌표가 응시자인 경우 false
        2. 다음 좌표가 빈자리인 경우 
          1. 옆자리에 응시자가 있는경우 : false
      2. 이 외의 경우 true

 

import java.util.*;

class Solution {
    // 상좌우하
    private static final int[] dx = {0,-1,1,0};
    private static final int[] dy = {-1,0,0,1};
    
    public int[] solution(String[][] places) {
        
        int[] answer = new int[places.length];
        
        for (int i=0; i<answer.length; i++) {
            String[] place = places[i];
            char[][] room = new char[place.length][];
        
            for (int j=0; j<room.length; j++) {
                room[j] = place[j].toCharArray();
            }
            
            // System.out.println(Arrays.deepToString(room));
            
            if (isDistanced(room)){
                answer[i]=1;
            }else{
                answer[i]=0;   
            }
        }
        return answer;
    }
    
    // 거리두기 검사
    private boolean isDistanced(char[][] room){

        for (int y=0; y<room.length; y++) {
            for (int x=0; x<room[y].length; x++) {
                if (room[y][x]!='P') continue; // 응시자인경우 검사
                if(!isDistanced(room,x,y)) return false;
            }
        }
        return true;
    }
    
    private boolean isDistanced(char[][] room, int x, int y){
        for (int d=0; d<4; d++) {
            int nx = x+dx[d];
            int ny = y+dy[d];
            
            if (ny<0 || ny>=room.length || nx<0 || nx>=room[ny].length) continue; // 좌표
            
            switch (room[ny][nx]){
                case 'P': return false; // 응시자인 경우
                case 'O': // 빈테이블인 경우
                    if (isNext(room,nx,ny,3-d)) return false; // 빈테이블 옆에 응시자인지 체크
                    // 3-d는 nx,ny에서 x,y로 오는방향(체크할 필요없음)
                    break;
            }
        }    
        return true;
    }
    
    private boolean isNext(char[][] room, int x, int y, int exclude){
        
        for (int d=0; d<4; d++){
            if (d==exclude) continue; // 이전 x,y로 가는 방향 제외
            
            int nx = x+dx[d];
            int ny = y+dy[d];
            if (ny<0 || ny>=room.length || nx<0 || nx>=room[ny].length) continue; // 좌표
            if (room[ny][nx]=='P') return true;
        }
        return false;        
    }
}
# 방향: 상좌우하
dx = [0, -1, 1, 0]
dy = [-1, 0, 0, 1]

def solution(places):
    answer = []
    
    for place in places:
        room = [list(row) for row in place]
        if isDistanced(room):
            answer.append(1)
        else:
            answer.append(0)
    return answer

# 전체 방이 거리두기를 준수하는지 검사
def isDistanced(room):
    for y in range(len(room)):
        for x in range(len(room[y])):
            if room[y][x] != 'P':
                continue
            if not isDistancedFromPosition(room, x, y):
                return False
    return True

# 특정 위치 (x, y)가 거리두기를 준수하는지 검사
def isDistancedFromPosition(room, x, y):
    for d in range(4):
        nx, ny = x + dx[d], y + dy[d]
        
        if ny < 0 or ny >= len(room) or nx < 0 or nx >= len(room[ny]):
            continue
        
        if room[ny][nx] == 'P':
            return False
        if room[ny][nx] == 'O' and isNextToPerson(room, nx, ny, 3 - d):
            return False
    return True

# 특정 위치 (x, y) 주변에 사람이 있는지 검사 (이전 방향 제외)
def isNextToPerson(room, x, y, exclude):
    for d in range(4):
        if d == exclude:
            continue
        nx, ny = x + dx[d], y + dy[d]
        
        if ny < 0 or ny >= len(room) or nx < 0 or nx >= len(room[ny]):
            continue
        if room[ny][nx] == 'P':
            return True
    return False

 

728x90