Advertisement
Josif_tepe

Untitled

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