[프로그래머스] 2021 카카오 | 거리두기 확인하기

윤득렬·2022년 5월 13일
0

풀기 전 생각 정리

  • 내 생각 / P를 기준으로
  1. 대기실 5개, 각 대기실은 5*5이므로 3중 for문을 돌려 P(응시자) 위치를 저장하는 list를 만들어 거리를 측정하자.
  2. P list를 돌려 맨해튼 거리가 2이하인 경우, 파티션의 유무를 체크해보자.

  • 다른 분의 tip / P를 기준으로 생각하지 않는다
  1. O(빈 테이블)을 기준으로 상하좌우에 P가 1개 이하인지 판단
  2. P를 기준으로 상하좌우에 P가 없는지 판단
    위 모든 조건을 충족하면 거리두기가 문제 없는 것

코드

def first_check(arr, o_pos): // O 기준 상하좌우 P 1개 이하인지
    dx = [0, 0, 1, -1]
    dy = [-1, 1, 0, 0]

    for o in o_pos:
        x, y = o[0], o[1]
        count = 0
        for i in range(4):
            t_x, t_y = x+dx[i], y+dy[i]
            if 0 <= t_x <= 4 and 0 <= t_y <= 4 and arr[t_x][t_y] == "P":
                count += 1
        if count >= 2:
            return False

    return True
    
def second_check(arr, p_pos): // P 기준 상하좌우 P가 존재하는지
    dx = [0, 0, 1, -1]
    dy = [-1, 1, 0, 0]

    for p in p_pos:
        x, y = p[0], p[1]
        for i in range(4):
            t_x, t_y = x + dx[i], y + dy[i]
            if 0 <= t_x <= 4 and 0 <= t_y <= 4 and arr[t_x][t_y] == "P":
                return False
    return True


def solution(places):
    answer = []

    for place in places:
        p_pos = []
        o_pos = []
        arr = []
        for i in range(5):
            arr.append(list(place[i]))

        for i in range(5):
            for j in range(5):
                if arr[i][j] == "P":
                    p_pos.append([i, j])
                elif arr[i][j] == "O":
                    o_pos.append([i, j])

        if first_check(arr, o_pos):
            if second_check(arr, p_pos):
                answer.append(1)
            else:
                answer.append(0)
        else:
            answer.append(0)
    return answer

리뷰

  • 문제를 읽고 기준이 될 변수를 특정 짓지 말고 모든 변수를 확인하자.
  • 기준이 될 변수를 정하고, 예외가 존재하는지 확인
profile
Backend server 개발자가 되고 싶은

0개의 댓글