Advertisement
Hamoudi30

Untitled

Aug 6th, 2021
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.27 KB | None | 0 0
  1.  
  2. //BFS
  3. vector<int> BFS (int st_node) {
  4.     vector<int> level(N, inf);  // nodes
  5.     queue<pair<int, int>> q;
  6.     q.push({st_node, 0});
  7.     level[st_node] = 0;
  8.     int cur_depth, cur_node;
  9.     while (not q.empty()) {
  10.         cur_node = q.front().first;
  11.         cur_depth = q.front().second;
  12.         q.pop();
  13.         for (int neg : adj[cur_node]) {
  14.             // neg : node
  15.             if (level[neg] == inf) {
  16.                 // not visited before
  17.                 q.push({neg, cur_depth + 1});
  18.                 level[neg] = cur_depth + 1;
  19.             }
  20.         }
  21.     }
  22.     return level;
  23. }
  24.  
  25. // BFS 2  half memory usage
  26. vector<int> BFS2 (int st_node) {
  27.     vector<int> dist(N, inf);
  28.     queue<int> q;
  29.     q.push(st_node);
  30.     dist[st_node] = 0;
  31.     int lvl = 0, cur_node = st_node, sz_q = SZ(q);
  32.     for (; !q.empty(); lvl++, sz_q = SZ(q)) {
  33.         while (sz_q--) {
  34.             cur_node = q.front();
  35.             q.pop();
  36.             for (int neg : adj[cur_node]) {
  37.                 if (dist[neg] == inf) {
  38.                     // not visited before
  39.                     q.push(neg);
  40.                     dist[neg] = lvl + 1;
  41.                 }
  42.             }
  43.         }
  44.     }
  45.     return dist;
  46. }
  47.  
  48.  
  49. // BFS path
  50. vector<int> BFSPath (int st_node, int target) {
  51.     vector<int> dist(N, inf);
  52.     vector<int> parent(N, -1);
  53.     queue<int> q;
  54.     q.push(st_node);
  55.     dist[st_node] = 0;
  56.     int lvl = 0, cur_node = st_node, sz_q = SZ(q);
  57.     bool found = false;
  58.     for (; not found && SZ(q); lvl++, sz_q = SZ(q)) {
  59.         while (not found && sz_q--) {
  60.             cur_node = q.front();
  61.             q.pop();
  62.             for (int neg : adj[cur_node]) {
  63.                 if (dist[neg] == inf) {
  64.                     // not visited before
  65.                     dist[neg] = lvl + 1;
  66.                     q.push(neg);
  67.                     // path
  68.                     parent[neg] = cur_node;
  69.                     if (neg == target) {
  70.                         found = true;
  71.                         break;
  72.                     }
  73.                 }
  74.             }
  75.         }
  76.     }
  77.     vector<int> path;
  78.     while (target != -1) {
  79.         path.push_back(target);
  80.         // update
  81.         target = parent[target];
  82.     }
  83.     reverse(path.begin(), path.end());
  84.     return path;
  85. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement