Skip to main content

DFS using a stack

#include<bits/stdc++.h>
using namespace std;
class graph
{
    int v;
    list<int> *adj;
public:
    graph(int v)
    {
        this->v=v;
        adj=new list<int>[v];
    }
    void add_edge(int v,int w)
    {
        adj[v].push_back(w);
    }
    void dfs(int start);
};
void graph:: dfs(int start)
{
    bool *visited=new bool[v];
    for(int i=0;i<v;i++)
        visited[i]=false;
    visited[start]=true;
    stack<int> s;
    s.push(start);
    while(!s.empty())
    {
        int k=s.top();
        s.pop();
        cout<<k<<" ";
        for(auto itr=adj[k].begin();itr!=adj[k].end();itr++)
        {
            if(!visited[*itr])
            {
                visited[*itr]=true;
                s.push(*itr);
            }
        }
    }
}
int main()
{
    int v;
    cout<<"Enter the number of vertices"<<endl;
    cin>>v;
    graph g(v);
    while(1)
    {
        int x,y;
        cout<<"Enter the nodes"<<endl;
        cin>>x>>y;
        g.add_edge(x,y);
        cout<<"Enter -1 to exit"<<endl;
        int t;
        cin>>t;
        if(t==-1)
            break;
    }
    cout<<"Enter the starting node"<<endl;
    int t;
    cin>>t;
    g.dfs(t);
    return 0;
}

Comments

Popular posts from this blog

Gcd using recursion

#include<iostream> #include<algorithm> using namespace std; int gcd(int m,int n) {     if(max(m,n)%min(m,n)==0)     {         return min(m,n);     }     else     {         gcd(max(m,n)%min(m,n),min(m,n));     } } int main() {     int m,n;     cin>>m>>n;     cout<<gcd(m,n);     return 0; }

Finding permutations of a string using recursion

#include<bits/stdc++.h> using namespace std; void print_perm(char str[],int k,int n) {     if(k==n)         cout<<str<<endl;     else     {         for(int i=k;i<n;i++)         {             swap(str[k],str[i]);             print_perm(str,k+1,n);             swap(str[k],str[i]);         }     } } int main() {     char str[20];     cout<<"Enter a string"<<endl;     cin>>str;     print_perm(str,0,strlen(str));     return 0; }

Counting the number of strongly connected sub graph

#include<bits/stdc++.h> using namespace std; class graph {     int v;     list<int> *adj; public:     graph(int v)     {         this->v=v;         adj=new list<int>[v];     }     void add_edge(int v,int w)     {         adj[v].push_back(w);         adj[w].push_back(v);     }     void dfs(int start,bool visited[]);     void counted(int start); }; void graph:: dfs(int start,bool visited[]) {     visited[start]=true;     for(auto it=adj[start].begin();it!=adj[start].end();it++)     {         if(!visited[*it])         {             dfs(*it,visited);  ...