Skip to content

Commit

Permalink
Added solution - LeetHub
Browse files Browse the repository at this point in the history
  • Loading branch information
sainikcodes24x7 committed Jul 2, 2023
1 parent 23f6f92 commit 662b11a
Showing 1 changed file with 59 additions and 0 deletions.
59 changes: 59 additions & 0 deletions DFS of Graph - GFG/dfs-of-graph.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
//{ Driver Code Starts
#include <bits/stdc++.h>
using namespace std;

// } Driver Code Ends
class Solution {
public:
// Function to return a list containing the DFS traversal of the graph.
vector<int>ans;
void dfs(int node, vector<bool>&vis, vector<int>adj[],int V){
vis[node]=true;
ans.push_back(node);
for(auto nbr:adj[node]){
if(!vis[nbr]){
dfs(nbr,vis,adj,V);
}
}
}
vector<int> dfsOfGraph(int V, vector<int> adj[]) {
// Code here
vector<bool>vis(V+1,false);
//vis[0]=true;
for(int i=0;i<V;i++){
if(!vis[i]){
dfs(i,vis,adj,V);
}
}
return ans;
}
};

//{ Driver Code Starts.
int main() {
int tc;
cin >> tc;
while (tc--) {
int V, E;
cin >> V >> E;

vector<int> adj[V];

for (int i = 0; i < E; i++) {
int u, v;
cin >> u >> v;
adj[u].push_back(v);
adj[v].push_back(u);
}
// string s1;
// cin>>s1;
Solution obj;
vector<int> ans = obj.dfsOfGraph(V, adj);
for (int i = 0; i < ans.size(); i++) {
cout << ans[i] << " ";
}
cout << endl;
}
return 0;
}
// } Driver Code Ends

0 comments on commit 662b11a

Please sign in to comment.