|
| 1 | +/* |
| 2 | +*************************** |
| 3 | +* * |
| 4 | +* Author: Swaraj Deep * |
| 5 | +* * |
| 6 | +*************************** |
| 7 | +*/ |
| 8 | + |
| 9 | +#include <iostream> |
| 10 | +#include <vector> |
| 11 | +#include <queue> |
| 12 | +#include <climits> |
| 13 | +#define pi pair<int, int> |
| 14 | + |
| 15 | +using namespace std; |
| 16 | + |
| 17 | +// Single Source Shortest Path when weight is either zero or one |
| 18 | +void zero_one_bfs(vector<vector<pi>> &graph, vector<int> &distance, int root, int dist = 0) |
| 19 | +{ |
| 20 | + distance[root] = dist; |
| 21 | + deque<int> dq; // Deque for storing nodes |
| 22 | + dq.push_front(root); |
| 23 | + while (!dq.empty()) |
| 24 | + { |
| 25 | + int vertex = dq.front(); |
| 26 | + dq.pop_front(); |
| 27 | + for (pi child : graph[vertex]) |
| 28 | + { |
| 29 | + int u = child.first; |
| 30 | + int w = child.second; |
| 31 | + // if adding this edge relaxes the previous cost then update it |
| 32 | + if (distance[vertex] + w < distance[u]) |
| 33 | + { |
| 34 | + distance[u] = distance[vertex] + w; |
| 35 | + // Keep the nodes in sorted order i.e. if weight is one this node is one level down else it is at the same level |
| 36 | + if (w == 1) |
| 37 | + { |
| 38 | + dq.push_back(u); |
| 39 | + } |
| 40 | + else |
| 41 | + { |
| 42 | + dq.push_front(u); |
| 43 | + } |
| 44 | + } |
| 45 | + } |
| 46 | + } |
| 47 | +} |
0 commit comments