Advertisement
kazi_omar

bfs

Mar 11th, 2021
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.67 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. int bfs(int s, int dest, int node, vector<int> v[])
  5. {
  6.     int vis[node + 1];
  7.     memset(vis, -1, sizeof(vis));
  8.     queue<int> q;
  9.     q.push(s);
  10.     vis[s] = 0;
  11.     int peak = 0;
  12.     while (!q.empty())
  13.     {
  14.         peak = q.front();
  15.  
  16.         // cout << "parent: " << q.front() << "; not visited child: ";
  17.  
  18.         q.pop();
  19.         for (int i = 0; i < v[peak].size(); i++)
  20.         {
  21.             if (vis[v[peak][i]] == -1)
  22.             {
  23.                 // cout << v[peak][i] << " ";
  24.  
  25.                 vis[v[peak][i]] = vis[peak] + 1;
  26.                 q.push(v[peak][i]);
  27.  
  28.                 // if (i == v[peak].size() - 1)
  29.                 // {
  30.                 //     cout << "; dis from "
  31.                 //          << "source " << s << ": " << vis[peak] + 1;
  32.                 // }
  33.             }
  34.         }
  35.         // cout << endl;
  36.     }
  37.     return vis[dest];
  38. }
  39.  
  40. int main()
  41. {
  42.     int node, edge;
  43.     // cout << "path from source --> destination: " << endl;
  44.     cin >> node >> edge;
  45.     vector<int> v[node + 1];
  46.     int s, d;
  47.     for (int i = 0; i < edge; i++)
  48.     {
  49.         cin >> s >> d;
  50.         v[s].push_back(d);
  51.         v[d].push_back(s);
  52.     }
  53.  
  54.     // for (int i = 1; i <= node; i++)
  55.     // {
  56.     //     cout << i << "--> ";
  57.     //     for (int j = 0; j < v[i].size(); j++)
  58.     //     {
  59.     //         cout << v[i][j] << " ";
  60.     //     }
  61.     //     cout << endl;
  62.     // }
  63.     // cout << endl;
  64.  
  65.     int source, dest;
  66.     cin >> source >> dest;
  67.     // cout << "min distance from source " << source << " to " << dest << ": " << endl;
  68.  
  69.     cout << bfs(source, dest, node, v);
  70.  
  71.     return 0;
  72. }
  73.  
  74.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement