Coaspe

알고리즘/Programmers - 양과 늑대(Python3) 본문

알고리즘

알고리즘/Programmers - 양과 늑대(Python3)

Coaspe 2022. 11. 15. 14:26
import collections

answer = 0

def solution(info, edges):
    graph = collections.defaultdict(list)
    
    for src, dst in edges:
        graph[src].append(dst)
    
    def dfs(s, sheep, wolf, path):
    	# 양, 늑대 확인
        if not info[s]: sheep += 1
        else: wolf += 1
        if wolf >= sheep: return
    
        global answer
        answer = max(answer, sheep)
        
        # 직후 DFS에서는 현재 노드를 탐색할 필요가 없다.
        if path: path.remove(s)
        path.extend(graph[s])
        
        for i in path:
            dfs(i, sheep, wolf, path[:])
    
    dfs(0, 0, 0, [])
    
    return answer

DFS를 사용한 풀이 입니다.

Comments