Advertisement
Singasking

Untitled

Sep 30th, 2022
207
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.94 KB | None | 0 0
  1. //Code to find all possible paths from given source to dest
  2. #include <bits/stdc++.h>
  3. using namespace std;
  4. const int N = 1e5;
  5. int vis[N];
  6.  
  7. vector<int> adj[N];
  8.  
  9. vector<vector<int>> paths;
  10. void dfs(int source,int target,vector<int> path) {
  11. vis[source]=1;
  12. path.push_back(source);
  13. if(source==target) {
  14. //We have found a valid path
  15. //Append current path copy to paths
  16. paths.push_back(path);
  17. } else {
  18.  
  19. for(auto it:adj[source]) {
  20. if(vis[it]==false or it==target) {
  21. // cout<<"Checking neighbour "<<it<<" of "<<source<<endl;
  22. dfs(it,target,path);
  23. }
  24.  
  25. }
  26. }
  27. }
  28.  
  29. int main() {
  30. int V,E;
  31. cin>>V>>E;
  32. for(int i=0;i<E;i++) {
  33. int x,y;
  34. cin>>x>>y;
  35. adj[x].push_back(y);
  36. adj[y].push_back(x);
  37. }
  38. int source,dest;
  39. cin>>source>>dest;
  40. vector<int> path;
  41. dfs(source,dest,path);
  42. for(auto p:paths) {
  43. for(auto it:p) {
  44. cout<<it<<" ";
  45. }
  46. cout<<endl;
  47. }
  48. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement