Coding Global Background
Coding Global

Try to implement BFS in Graph but not showing any output..

Archiviert 2 years ago
6 Nachrichten
1 Mitglieder
Erstellt 3 years ago
Aktualisiert 3 years ago
In Discord öffnen
P
Pradhuman Thakurela
Verified
#include <iostream>
#include <vector>
#include <unordered_map>
#include <list>
#include <queue>

using namespace std;

class graph
{
public:
    unordered_map<int, bool> visited;
    void addEdge(int u, int v, bool direction);
    vector<int>BFS(unordered_map<int, list<int>> adj, int node);
    void BFSIN(unordered_map<int, list<int>> adj,int vertex);
};

void graph ::addEdge(int u, int v, bool direction)
{
    unordered_map<int, list<int>> adj;

    adj[u].push_back(v);

    if (direction == 0)
    {
        adj[v].push_back(u);
    }
}

vector<int> graph ::BFS(unordered_map<int, list<int>> adj, int node)
{
    int front;
    queue<int> q;
    vector<int> result;
    q.push(node);
    visited[node] = true;

    while (q.empty() == false)
    {
        front = q.front();
        result.push_back(front);
        q.pop();
    }
    for (auto i : adj[front])
    {
        if (!visited[i])
        {
            q.push(i);
            visited[i] = true;
            result.push_back(i);
        }
    }
    return result;
}

void graph :: BFSIN(unordered_map<int, list<int>> adj,int vertex)
{
    for (int  i = 0; i < vertex; i++)
    {
       if (visited[i]==false)
       {
       BFS(adj,i);
       }
       
    }
    
}
int main()
{  
    int vertex = 7;
    unordered_map<int , list<int>>adj;
    graph g;
    g.addEdge(0,2,0); 
    g.addEdge(2,3,0); 
    g.addEdge(1,3,0); 
    g.addEdge(4,5,0);
    g.addEdge(5,6,0);
    g.addEdge(4,6,0);

    cout << "Following is Breadth First Traversal: "<< endl; 
    g.BFSIN( adj,vertex); 


    return 0;
}

Antworten (7)