Complete-Preparation

πŸŽ‰ One-stop destination for all your technical interview Preparation πŸŽ‰

View the Project on GitHub

797. All Paths From Source to Target 🌟🌟

Given a directed acyclic graph (DAG) of n nodes labeled from 0 to n - 1, find all possible paths from node 0 to node n - 1 and return them in any order.

The graph is given as follows: graph[i] is a list of all nodes you can visit from node i (i.e., there is a directed edge from node i to node graph[i][j]).

BFS

This process can be implemented using a BFS traversal as -

Code

class Solution {
public:
    vector<vector<int>> allPathsSourceTarget(vector<vector<int>>& graph)
    {
        vector<vector<int>> ans;
        queue<vector<int>> q;

        q.push({ 0 }); // push the initial source
        while (q.size()) {
            auto path = move(q.front()); // efficiently copy (pointer copy)
            q.pop();

            if (path.back() == graph.size() - 1) // found valid path
                ans.push_back(move(path));
            else
                for (auto x : graph[path.back()]) { // try every possible next node in path
                    path.push_back(x);
                    q.push(path); // push path into queue for further exploration
                    path.pop_back();
                }
        }
        return ans;
    }
};

DFS - Backtracking

The process of finding all paths using DFS can be implemented as -

Code

class Solution {
private:
    void dfs(int src, int dest, vector<vector<int>>& graph, vector<int>& curr, vector<vector<int>>& ans)
    {
        if (src == dest) { // base condition - found a path
            ans.push_back(curr);
            return;
        }
        for (int x : graph[src]) {
            curr.push_back(x); // DO
            dfs(x, dest, graph, curr, ans); // RECUR
            curr.pop_back(); // UNDO/Backtrack
        }
    }

public:
    vector<vector<int>> allPathsSourceTarget(vector<vector<int>>& graph)
    {
        vector<vector<int>> ans;
        vector<int> curr;

        curr.push_back(0); // push the initial source
        dfs(0, graph.size() - 1, graph, curr, ans); // dfs(src,dest,graph,curr,ans)

        return ans;
    }
};