Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- BFS : O(E + V) .. shortetst path from source vertetx to another .. (unweighted graph ***)
- */
- unordered_map<int,vector<int>> adj; // adjacency list representation
- int n; // number of nodes
- int s; // source vertex given
- queue<int> q;
- vector<bool> used(n); // visited array
- vector<int> d(n), p(n); // d is distance vertex and p is parent vertex ..
- q.push(s);
- used[s] = true;
- p[s] = -1; // parent of source vertex is -1
- while (!q.empty()) {
- int v = q.front();
- q.pop();
- for (int u : adj[v]) {
- if (!used[u]) {
- used[u] = true;
- q.push(u);
- d[u] = d[v] + 1;
- p[u] = v;
- }
- }
- }
- /// printing the shortets path from source to any vertex u ..
- if (!used[u]) {
- cout << "No path!";
- } else {
- vector<int> path;
- for (int v = u; v != -1; v = p[v])
- path.push_back(v);
- reverse(path.begin(), path.end());
- cout << "Path: ";
- for (int v : path)
- cout << v << " ";
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement