ps | |
---|---|
링크 | programmers.co.kr/… |
출처 | 프로그래머스 |
문제 번호 | 49190 |
문제명 | 방의 개수 |
레벨 | Level 5 |
분류 |
오일러 공식 |
시간복잡도 | O(n) |
인풋사이즈 | n<=100,000 |
사용한 언어 | Python |
해결날짜 | 2021/01/22 |
태그 |
"""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
"""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