josiftepe

Untitled

Nov 28th, 2020
48
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.33 KB | None | 0 0
  1. #include <iostream>
  2. #include <cmath>
  3. #include <vector>
  4. #include <queue>
  5. using namespace std;
  6. typedef long long ll;
  7. const int maxn = 1e5 + 10;
  8. vector<int> graph[maxn];
  9. int n, m;
  10. int bfs(int S, int E) {
  11.     queue<int> q;
  12.     q.push(S); // current node
  13.     q.push(0); // shortest distance from starting node to current node
  14.     vector<bool> visited(n + 1, false);
  15.     visited[S] = true;
  16.     while(!q.empty()) {
  17.         int current_node = q.front(); q.pop();
  18.         int shortest_distance_from_start_till_now = q.front(); q.pop();
  19.         if(current_node == E) {
  20.             return shortest_distance_from_start_till_now;
  21.         }
  22.         for(int i = 0; i < (int) graph[current_node].size(); ++i) {
  23.             int neighbour = graph[current_node][i];
  24.             if(!visited[neighbour]) {
  25.                 visited[neighbour] = true;
  26.                 q.push(neighbour);
  27.                 q.push(shortest_distance_from_start_till_now + 1);
  28.             }
  29.         }
  30.     }
  31.     return -1;
  32. }
  33. int main()
  34. {
  35.     ios_base::sync_with_stdio(false);
  36.     cin >> n >> m;
  37.     for(int i = 0; i < m; ++i) {
  38.         int a, b;
  39.         cin >> a >> b;
  40.         graph[a].push_back(b);
  41.         graph[b].push_back(a);
  42.         //undirected graph
  43.     }
  44.     int start, end;
  45.     cin >> start >> end;
  46.     cout << bfs(start, end) << endl;
  47.     return 0;
  48. }
Advertisement
Add Comment
Please, Sign In to add comment