Skip to main content

Command Palette

Search for a command to run...

Graph - All Paths From Source to Target

Published
1 min read
Graph - All Paths From Source to Target
N

I am Nirbhay Singh , I am starting this blog to document my coding journey of becoming a software developer and to get my first $ 100k offer .

All Paths From Source to Target

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

Hint:

Solution:

// TIME COMPLEXITY : O(N+E);
//SPACE COMPLEXITY : O(N) + Auxiliary Space O(N)


class Solution {
public:
    void dfs(vector<vector<int>> &adj, int src, int dest, 
    vector<int> &temp, vector<vector<int>> &output){

        if(src==dest){
            output.push_back(temp);
            return;
        }

        for(auto it: adj[src]){
            if(it!=src){
                temp.push_back(it);
                dfs(adj,it,dest,temp,output);
                temp.pop_back();
            }
        }
        return;

    }
    vector<vector<int>> allPathsSourceTarget(vector<vector<int>>& graph) {
        vector<vector<int>> output;
        vector<int> temp;

        int n = graph.size();

        temp.push_back(0);
        dfs(graph,0,n-1,temp,output);

        return output;
    }
};

DSA prep

Part 8 of 22

This series is specifically to document and share my learning of Data Structure and Algorithms and building the programmers intuition to solve a problem through coding and getting my first job as SDE.

Up next

Product of Array Except Self

Product of Array Except Self Problem Link: https://leetcode.com/problems/product-of-array-except-self/description/ Hint: https://www.loom.com/share/c0477a0822e343ecb2dfee244488cc4e?sid=d36dbb54-70a3-4f80-90e9-18b9ba244f76 Code: class Solution { pub...

More from this blog

Daily Code by Nirbhay

74 posts

Hey, this is Nirbhay. I started this blog to document my journey of learning to code and get my first $100k offer. I'll be sharing the things related to DSA, backend development, devops and many more.