ronith
9/28/2018 - 12:28 PM

BFS

#include <iostream>
using namespace std;

class graph {
    int v;
    int **adj;
public:
    graph (int v) {
        this->v= v;
        adj= new int*[v];
        for (int i=0; i<v; i++)
            adj[i]= new int [v];
        for (int i=0; i<v; i++)
            for (int j=0; j<v; j++)
                adj[i][j]= 0;
    }
    void addEdge (int u, int w) {
        adj[u][w]= 1;
    }
    void bfs (int );
};
void graph::bfs(int s) {
    bool visited[v]= {0};
    int q[v], front=0, back=0,x;
    q[back++]= s;
    while (front< back) {
        x= q[front++];
        visited[x]= 1;
        cout<< x << " ";

        for (int j=0; j<v; j++)
            if (adj[x][j]== 1 & !visited[j])
                q[back++]= j;
    }
}
int main() {
    graph g(4);
    g.addEdge(0,1);
    g.addEdge(0,2);
    g.addEdge(1,2);
    g.addEdge(2,0);
    g.addEdge(2,3);
    g.addEdge(3,3);

    g.bfs(2);
}