Josif_tepe

Untitled

Aug 13th, 2025
376
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.06 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<int> q;
  11.     q.push(S);
  12.     q.push(0);
  13.    
  14.     vector<bool> visited(n + 1, false);
  15.     visited[S] = true;
  16.    
  17.     while(!q.empty()) {
  18.         int node = q.front();
  19.         q.pop();
  20.         int dist = q.front();
  21.         q.pop();
  22.        
  23.         if(node == E) {
  24.             cout << dist << endl;
  25.             break;
  26.         }
  27.        
  28.         for(int neighbour : graph[node]) {
  29.             if(!visited[neighbour]) {
  30.                 visited[neighbour] = true;
  31.                 q.push(neighbour);
  32.                 q.push(dist + 1);
  33.             }
  34.         }
  35.        
  36.     }
  37. }
  38. int main() {
  39.     ios_base::sync_with_stdio(false);
  40.    
  41.     cin >> n >> m;
  42.    
  43.     for(int i = 0; i < m; i++) {
  44.         int a, b;
  45.         cin >> a >> b;
  46.         graph[a].push_back(b);
  47.         graph[b].push_back(a);
  48.     }
  49.    
  50.     int S, E;
  51.     cin >> S >> E;
  52.     bfs(S, E);
  53.     return 0;
  54. }
  55.  
Advertisement
Add Comment
Please, Sign In to add comment