Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //Code to find all possible paths from given source to dest
- #include <bits/stdc++.h>
- using namespace std;
- const int N = 1e5;
- int vis[N];
- vector<int> adj[N];
- vector<vector<int>> paths;
- void dfs(int source,int target,vector<int> path) {
- path.push_back(source);
- if(source==target) {
- //We have found a valid path
- //Append current path copy to paths
- paths.push_back(path);
- } else {
- vis[source]=1;
- for(auto it:adj[source]) {
- if(vis[it]==false or it==target) {
- // cout<<"Checking neighbour "<<it<<" of "<<source<<endl;
- dfs(it,target,path);
- }
- }
- vis[source]=false;
- }
- }
- int main() {
- int V,E;
- cin>>V>>E;
- for(int i=0;i<E;i++) {
- int x,y;
- cin>>x>>y;
- adj[x].push_back(y);
- adj[y].push_back(x);
- }
- int source,dest;
- cin>>source>>dest;
- vector<int> path;
- dfs(source,dest,path);
- for(auto p:paths) {
- for(auto it:p) {
- cout<<it<<" ";
- }
- cout<<endl;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement