목차

동굴 탐험

ps
링크programmers.co.kr/…
출처프로그래머스
문제 번호67260
문제명동굴 탐험
레벨Level 4
분류

그래프, 사이클 찾기

시간복잡도O(n)
인풋사이즈n<=200,000
사용한 언어Python
해결날짜2020/12/23

풀이

코드

"""Solution code for "Programmers 67260. 동굴 탐험".

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


def solution(n, path, order):
    graph = [[] for _ in range(n)]
    indegrees = [1] * n
    indegrees[0] = 0
    for u, v in path:
        graph[u].append(v)
        graph[v].append(u)
    for u, v in order:
        graph[u].append(v)
        indegrees[v] += 1

    if indegrees[0] > 0:
        return False
    stack = [0]
    visited_room_count = 0
    while stack:
        u = stack.pop()
        visited_room_count += 1
        for v in graph[u]:
            indegrees[v] -= 1
            if indegrees[v] == 0:
                stack.append(v)

    return visited_room_count == n