소프트웨어에 대한 모든 것

LeetCode 풀기 - 797. All Paths From Source to Target 본문

알고리즘/LeetCode

LeetCode 풀기 - 797. All Paths From Source to Target

앤테바 2021. 11. 8. 21:41
반응형

797. All Paths From Source to Target

https://leetcode.com/problems/all-paths-from-source-to-target/

 

All Paths From Source to Target - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

문제)

 

솔루션1)

DFS 방법을 이용해서 재귀적으로 path를 탐색한다.

class Solution:
    def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]:
        target = len(graph) - 1
        paths = []
        
        def dfs(node, path):
            if node == target:
                paths.append(path.copy())
                return
            
            for neighbor in graph[node]:
                dfs(neighbor, path + [neighbor])
            
        dfs(0, [0])         
        return paths

 

반응형
Comments