목차

방의 개수

ps
링크programmers.co.kr/…
출처프로그래머스
문제 번호49190
문제명방의 개수
레벨Level 5
분류

오일러 공식

시간복잡도O(n)
인풋사이즈n<=100,000
사용한 언어Python
해결날짜2021/01/22
태그

고득점 Kit - 그래프

풀이

기존에 적었던 풀이

코드

코드 1 - 최신 방식 (이동을 모두 마치고 방의 갯수를 계산)

"""Solution code for "Programmers 49190. 방의 개수".

- Problem link: https://programmers.co.kr/learn/courses/30/lessons/49190
- Solution link: http://www.teferi.net/ps/problems/programmers/49190
"""

MOVES_BY_ARROW = [(0, -1), (1, -1), (1, 0), (1, 1), (0, 1), (-1, 1), (-1, 0),
                  (-1, -1)]


def solution(arrows):
    cur_point = (0, 0)
    edges = set()
    points = set([cur_point])
    for arrow in arrows:
        dx, dy = MOVES_BY_ARROW[arrow]
        for _ in range(2):
            next_point = (cur_point[0] + dx, cur_point[1] + dy)
            points.add(next_point)
            edges.add((min(cur_point, next_point), max(cur_point, next_point)))
            cur_point = next_point
    # from Euler's formula, V-E+F=2
    return len(edges) - len(points) + 1

코드 2 - 예전 방식 (이동할 때마다 체크해서 방의 갯수를 갱신)

"""Solution code for "Programmers 49190. 방의 개수".

- Problem link: https://programmers.co.kr/learn/courses/30/lessons/49190
- Solution link: http://www.teferi.net/ps/problems/programmers/49190
"""

import collections

MOVES_BY_ARROW = [(0, -1), (1, -1), (1, 0), (1, 1), (0, 1), (-1, 1), (-1, 0),
                  (-1, -1)]


def solution(arrows):
    neighbors_by_point = collections.defaultdict(set)
    room_count = 0
    point = (0, 0)
    neighbors_by_point[point] = set()
    for arrow in arrows:
        for _ in range(2):
            new_point = (point[0] + MOVES_BY_ARROW[arrow][0],
                         point[1] + MOVES_BY_ARROW[arrow][1])
            if ((neighbors := neighbors_by_point.get(new_point)) is not None and
                    point not in neighbors):
                room_count += 1
            neighbors_by_point[new_point].add(point)
            neighbors_by_point[point].add(new_point)
            point = new_point
    return room_count