Skip to main content

DFS of a 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);
    }
    void dfs(int v);
    void dfsSearch(int v,bool visited[]);
};
void graph:: dfsSearch(int start,bool visited[])
{
    visited[start]=true;
    cout<<start<<" ";
    for(auto itr=adj[start].begin();itr!=adj[start].end();itr++)
    {
        if (!visited[*itr])
        {
            dfsSearch(*itr,visited);
        }
    }
}
void graph:: dfs(int start)
{
    bool *visited=new bool[v];
    for(int i=0;i<v;i++)
        visited[i]=false;
    dfsSearch(start,visited);
}
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; }

Bubble Sort Algorithm

//bubble sort algorithm in c++ #include<bits/stdc++.h> using namespace std; void bubble_sort(int arr[],int n) {     int i,j;     for(i=1;i<n;i++)     {         for(j=0;j<n-i;j++)         {             if(arr[j]>arr[j+1])             {                 swap(arr[j],arr[j+1]); //swap is an inbuilt function             }         }     }     //time complexity is O(n^2) } int main() {     int n,i;     cout<<"Enter the number of elements of the array"<<endl;     cin>>n;     int arr[n];     for(i=0;i<n;i++)     { ...

Counting the paths between two nodes

#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 count(int start,int end,bool visited[],int& path);     int  cou(int start,int end); }; int graph:: cou(int start,int end) {     bool *visited=new bool[v];     for(int i=0;i<v;i++)         visited[i]=false;     int path=0;     count(start,end,visited,path);     return path; } void graph::count(int start,int end,bool visited[],int& path) {     vi...