Graph Series: BFS Iterative Solution

KuldipMochi
Oct 26, 2024

--

vector<int> bfsOfGraph(vector<vector<int>> &adj) {
int source = 0;
int row = adj.size();
int col = adj[0].size();
vector<int> visitedNodes(row, 0);
vector<int> ans;
queue<int> q;
q.push(source);
visitedNodes[source] = 1;
while(!q.empty()){
int front = q.front();
q.pop();
ans.push_back(front);

for(int child: adj[front]){
if(visitedNodes[child]==0){
q.push(child);
visitedNodes[child] = 1;
}
}
}
return ans;
}

--

--

KuldipMochi
KuldipMochi

Written by KuldipMochi

Empath 🤗 Love to write ✍️

No responses yet