sophryu99 / algorithm

algorithm in python - 4 questions a week

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

797. All Paths From Source to Target

sophryu99 opened this issue · comments

commented

Approach

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

DFS through the DAG
Since the size of the input node is 2 <= n <= 15, the approach does not need to be super efficient

  1. Start from the first node and traverse through the directed edges by calling dfs iteratively
  2. Have the path saved as the parameter to the dfs function
  3. When the traversal reaches the end node (n), append the path to the result and end traversing
class Solution:
    def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]:
        
        def dfs(path):
            if path[-1] == len(graph) - 1:
                res.append(path)
                return
            
            for v in graph[path[-1]]:
                dfs(path + [v])

        res = []
        dfs([0])
        return res

n: number of edges

  • Time Complexity: O(n) - O(n^2) depending on the shape of the DAG
  • Space Complexity: O(n) as result array

https://leetcode.com/problems/all-paths-from-source-to-target/solutions/986429/python-iterative-dfs-with-detailed-time-complexity-visuals/?orderBy=most_votes