Created
June 24, 2022 05:23
-
-
Save webber2408/5b78c2a0add9836a6dd0d8819161ab1a to your computer and use it in GitHub Desktop.
DFS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <bits/stdc++.h> | |
using namespace std; | |
class Solution { | |
void dfs(int node, vector<int> &vis, vector<int> adj[], vector<int> &storeDfs) { | |
storeDfs.push_back(node); | |
vis[node] = 1; | |
for(auto it : adj[node]) { | |
if(!vis[it]) { | |
dfs(it, vis, adj, storeDfs); | |
} | |
} | |
} | |
public: | |
vector<int>dfsOfGraph(int V, vector<int> adj[]){ | |
vector<int> storeDfs; | |
vector<int> vis(V+1, 0); | |
for(int i = 1;i<=V;i++) { | |
if(!vis[i]) dfs(i, vis, adj, storeDfs); | |
} | |
return storeDfs; | |
} | |
}; | |
void addEdge(vector<int> adj[],int u,int v) | |
{ | |
adj[u].push_back(v); | |
adj[v].push_back(u); | |
} | |
int main() | |
{ | |
vector<int> adj[6]; | |
addEdge(adj,1,2); | |
addEdge(adj,1,3); | |
addEdge(adj,1,4); | |
addEdge(adj,1,5); | |
addEdge(adj,2,4); | |
addEdge(adj,2,1); | |
addEdge(adj,3,1); | |
addEdge(adj,4,1); | |
addEdge(adj,4,2); | |
addEdge(adj,5,1); | |
Solution obj; | |
vector<int> df; | |
df= obj.dfsOfGraph(5, adj); | |
for(auto it: df) | |
cout<<it<<" "; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment