Josif_tepe

Untitled

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