본문 바로가기
Programming/Programmers

[프로그래머스] 동굴 탐험 (Python)

by 데이터현 2021. 12. 9.

https://programmers.co.kr/learn/courses/30/lessons/67260

 

코딩테스트 연습 - 동굴 탐험

9 [[0,1],[0,3],[0,7],[8,1],[3,6],[1,2],[4,7],[7,5]] [[8,5],[6,7],[4,1]] true 9 [[8,1],[0,1],[1,2],[0,7],[4,7],[0,3],[7,5],[3,6]] [[4,1],[5,2]] true 9 [[0,1],[0,3],[0,7],[8,1],[3,6],[1,2],[4,7],[7,5]] [[4,1],[8,7],[6,5]] false

programmers.co.kr

DFS에 조건을 잘 걸어야 하는 문제다

 

from collections import defaultdict
import sys
sys.setrecursionlimit(1000000)
def solution(n, path, order):
    visited = [0]*n
    visited_count = 0
    graph = [[] for _ in range(n)]
    after = defaultdict(lambda : -1)
    ordered = [0]*n

    for p in path:
        start , end = p
        graph[start].append(end)
        graph[end].append(start)

    for o in order:
        pre, post = o
        ordered[post] = pre

    stack = [0]
    while stack:
        node = stack.pop()
        if ordered[node] and visited[ordered[node]] == False:
            after[ordered[node]] = node
            continue
        visited[node] = 1
        visited_count +=1
        for next in graph[node]:
            if visited[next] ==0:
                stack.append(next)
        if after[node] != -1:
            stack.append(after[node])
    return True if visited_count == n else False

댓글