All Paths From Source to Target in C++

C++Server Side ProgrammingProgramming

Suppose we have a directed, acyclic graph with N nodes. We have to find all possible paths from node 0 to node N-1, and return them in any order. The graph is given as follows: the nodes are 0, 1, ..., graph.length - 1. graph[i] is a list of all nodes j for which the edge (i, j) exists.

So if the input is like [[1,2], [3], [3], []], then the output will be [[0,1,3], [0,2,3]].

To solve this, we will follow these steps −

  • Make one 2d array called res

  • Define a method called solve, this will take graph, node, target and temp array

  • insert node into temp

  • if node is target, then insert temp into res and return

  • for i in range 0 to size of graph[node] – 1

    • call solve(graph, graph[node, i], target, temp)

  • From the main method create array temp, call solve(graph, 0, size of graph - 1, temp)

  • return res

Example(C++)

Let us see the following implementation to get a better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
void print_vector(vector<vector<auto> > v){
   cout << "[";
   for(int i = 0; i<v.size(); i++){
      cout << "[";
      for(int j = 0; j <v[i].size(); j++){
         cout << v[i][j] << ", ";
      }
      cout << "],";
   }
   cout << "]"<<endl;
}
class Solution {
   public:
   vector < vector <int> > res;
   void solve(vector < vector <int> >& graph, int node, int target, vector <int>temp){
      temp.push_back(node);
      if(node == target){
         res.push_back(temp);
         return;
      }
      for(int i = 0; i < graph[node].size(); i++){
         solve(graph, graph[node][i], target, temp);
      }
   }
   vector<vector<int>> allPathsSourceTarget(vector<vector<int>>& graph) {
      vector <int> temp;
      solve(graph, 0, graph.size() - 1, temp);
      return res;
   }
};
main(){
   vector<vector<int>> v = {{1,2},{3},{3},{}};
   Solution ob;
   print_vector(ob.allPathsSourceTarget(v));
}

Input

[[1,2],[3],[3],[]]

Output

[[0, 1, 3, ],[0, 2, 3, ],]
raja
Published on 02-May-2020 12:40:36
Advertisements