Advertisement
Josif_tepe

Untitled

Nov 15th, 2021
158
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.15 KB | None | 0 0
  1. #include <iostream>
  2. #include<ctime>
  3. #include<map>
  4. #include<vector>
  5. #include<queue>
  6. #include <algorithm>
  7. using namespace std;
  8. int main()
  9. {
  10.     int n, m;
  11.     cin >> n >> m;
  12.     vector<int> graph[n + 5];
  13.     bool visited[n + 5];
  14.     for(int i = 0; i <= n; i++) {
  15.         visited[i] = false;
  16.     }
  17.     for(int i = 0; i < m; i++) {
  18.         int a, b;
  19.         cin >> a >> b;
  20.         graph[a].push_back(b);
  21.         graph[b].push_back(a);
  22.     }
  23.     int S, T;
  24.     cin >> S >> T;
  25.    
  26.     queue<int> q;
  27.     q.push(S); // pocetno teme
  28.     q.push(0); // distanca od S do S
  29.     visited[S] = true;
  30.    
  31.     while(!q.empty()) {
  32.         int teme = q.front();
  33.         q.pop();
  34.         int dist = q.front();
  35.         q.pop();
  36.        
  37.         if(teme == T) {
  38.             cout << dist << endl;
  39.             return 0;
  40.         }
  41.        
  42.         for(int i = 0; i < graph[teme].size(); i++) {
  43.             int sosed = graph[teme][i];
  44.             if(!visited[sosed]) {
  45.                 q.push(sosed);
  46.                 q.push(dist + 1);
  47.                 visited[sosed] = true;
  48.             }
  49.         }
  50.        
  51.     }
  52.     cout << 0 << endl;
  53.     return 0;
  54. }
  55.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement