Josif_tepe

Untitled

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