All Paths from Source to Target (Leetcode 797)

Travel and Solve Recursion Pattern

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

from collections import defaultdict
class Solution:
    def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]:
        
        for i in range(len(graph)):
            graph[i].sort()
        
        adj=defaultdict(list)
        n=len(graph)
        for i in range(n):
            for j in graph[i]:
                adj[i].append(j)
                
        ans=[]
        
        def recursion(adj,src,dest,temp):
            
            if(src==dest):
                temp.append(dest)
                ans.append(temp)
                return
            
            for i in adj[src]:
                recursion(adj,i,dest,temp+[src])
        
        recursion(adj,0,n-1,[])
        return ans

Last updated