Skip to content

Instantly share code, notes, and snippets.

@dabasajay
Last active February 16, 2021 09:38
Show Gist options
  • Save dabasajay/e9949dec63f348da0dded4c3e150e2ac to your computer and use it in GitHub Desktop.
Save dabasajay/e9949dec63f348da0dded4c3e150e2ac to your computer and use it in GitHub Desktop.
dsa/graphs/traversal/ | desc: Breadth First Search
vector<vector<int>> adj; // adjacency list representation
int n; // number of nodes
int src; // source vertex
queue<int> q;
vector<bool> vis(n);
vector<int> dist(n), par(n);
q.push(src);
vis[src] = true;
par[src] = -1;
while (!q.empty()) {
int u = q.front();
q.pop();
for (int v : adj[u]) {
if (!vis[v]) {
vis[v] = true;
q.push(v);
dist[v] = dist[u] + 1;
par[v] = u;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment