File tree Expand file tree Collapse file tree 1 file changed +53
-0
lines changed Expand file tree Collapse file tree 1 file changed +53
-0
lines changed Original file line number Diff line number Diff line change
1
+ #include < bits/stdc++.h>
2
+ using namespace std ;
3
+
4
+
5
+ class Solution {
6
+ void dfs (int node, vector<int > &vis, vector<int > adj[], vector<int > &storeDfs) {
7
+ storeDfs.push_back (node);
8
+ vis[node] = 1 ;
9
+ for (auto it : adj[node]) {
10
+ if (!vis[it]) {
11
+ dfs (it, vis, adj, storeDfs);
12
+ }
13
+ }
14
+ }
15
+ public:
16
+ vector<int >dfsOfGraph (int V, vector<int > adj[]){
17
+ vector<int > storeDfs;
18
+ vector<int > vis (V+1 , 0 );
19
+ for (int i = 1 ;i<=V;i++) {
20
+ if (!vis[i]) dfs (i, vis, adj, storeDfs);
21
+ }
22
+ return storeDfs;
23
+ }
24
+ };
25
+
26
+
27
+ int main (){
28
+ int tc;
29
+ cin >> tc;
30
+ while (tc--){
31
+ int V, E;
32
+ cin >> V >> E;
33
+
34
+ vector<int > adj[V];
35
+
36
+ for (int i = 0 ; i < E; i++)
37
+ {
38
+ int u, v;
39
+ cin >> u >> v;
40
+ adj[u].push_back (v);
41
+ adj[v].push_back (u);
42
+ }
43
+ // string s1;
44
+ // cin>>s1;
45
+ Solution obj;
46
+ vector<int >ans=obj.dfsOfGraph (V, adj);
47
+ for (int i=0 ;i<ans.size ();i++){
48
+ cout<<ans[i]<<" " ;
49
+ }
50
+ cout<<endl;
51
+ }
52
+ return 0 ;
53
+ }
You can’t perform that action at this time.
0 commit comments