Complete-Preparation

🎉 One-stop destination for all your technical interview Preparation 🎉

View the Project on GitHub

Breadth first search(BFS)

Algorithm

Code

vector<int> bfs(int N, vector<int> adj[])
{
    vector<int> ans;
    vector<int> vis(N, 0);

    queue<int> q;
    q.push(0);
    vis[0] = 1;
    while (!q.empty()) {
        int node = q.front();
        q.pop();
        ans.push_back(node);
        for (auto it : adj[node]) {
            if (!vis[it]) {
                q.push(it);
                vis[it] = 1;
            }
        }
    }
    return ans;
}