Advertisement
Singasking

Untitled

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