jayati

DFS

Sep 2nd, 2023
1,028
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.39 KB | None | 0 0
  1. //{ Driver Code Starts
  2. #include <bits/stdc++.h>
  3. using namespace std;
  4.  
  5. // } Driver Code Ends
  6. class Solution {
  7.   public:
  8.     // Function to return a list containing the DFS traversal of the graph.
  9.    
  10.     void dfs(int start,vector<int> adj[],int vis[],vector<int> &ls)
  11.     {
  12.         vis[start]=1;
  13.         ls.push_back(start);
  14.         for(auto it:adj[start])
  15.         {
  16.             if(!vis[it])
  17.             {
  18.                 dfs(it,adj,vis,ls);
  19.             }
  20.         }
  21.        
  22.     }
  23.     vector<int> dfsOfGraph(int V, vector<int> adj[]) {
  24.         // Code here
  25.         int vis[V]={0};
  26.         int start=0;
  27.         vector<int> ls;
  28.         dfs(start,adj,vis,ls);
  29.         return ls;
  30.        
  31.     }
  32. };
  33.  
  34. //{ Driver Code Starts.
  35. int main() {
  36.     int tc;
  37.     cin >> tc;
  38.     while (tc--) {
  39.         int V, E;
  40.         cin >> V >> E;
  41.  
  42.         vector<int> adj[V];
  43.  
  44.         for (int i = 0; i < E; i++) {
  45.             int u, v;
  46.             cin >> u >> v;
  47.             adj[u].push_back(v);
  48.             adj[v].push_back(u);
  49.         }
  50.         // string s1;
  51.         // cin>>s1;
  52.         Solution obj;
  53.         vector<int> ans = obj.dfsOfGraph(V, adj);
  54.         for (int i = 0; i < ans.size(); i++) {
  55.             cout << ans[i] << " ";
  56.         }
  57.         cout << endl;
  58.     }
  59.     return 0;
  60. }
  61. // } Driver Code Ends
  62. //  https://practice.geeksforgeeks.org/problems/depth-first-traversal-for-a-graph/
Advertisement
Add Comment
Please, Sign In to add comment