bfs and dfs traversal code example

Example: bfs traversal code

#include <bits/stdc++.h>
using namespace std;
#define ll  long long int
#define ull unsigned long long int
void addedge(vector<int>adj[],int u,int v)
{
    adj[u].push_back(v);
    adj[v].push_back(u);
}
void print_list(vector <int> adj[],int n)
{
    for(int i=0;i<n;i++)
    {
        cout << "adjacency list for node" << i << "is :\n";
        for(auto ele: adj[i])
        {
            cout << "->" << ele << " \n";
        }

    }
}
void BFS(int v,int e,vector<int>adj[])
{
    bool visited[e];
    for(int i=0;i<e;i++)
    {
        visited[i]= false;
    }
    list<int>queue;
    visited[v]= true;
    queue.push_back(v);
    while (!queue.empty())
    {
        v = queue.front();
        cout << v << " ";
        queue.pop_front();
        for(auto ele:adj[v])
        {
            if(!visited[ele])
            {
                visited[ele]= true;
                queue.push_back(ele);

            }
        }
    }
}


int main()
{
    int n,e;
    cin >> n >> e;
    vector <int> adj[n];
    int u,v;
    for(int i=0;i<e;i++)
    {

        cin >> u >> v;
        addedge(adj,u,v);

    }
    print_list(adj,n);
    BFS(v,e,adj);


    return 0;
}

Tags:

Cpp Example