Advertisement
Josif_tepe

Untitled

Sep 29th, 2024
114
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 <vector>
  3. #include <queue>
  4. using namespace std;
  5. const int maxn = 1e5 + 10;
  6.  
  7. vector<int> graph[maxn];
  8. int main() {
  9.     int num_of_vertices;
  10.     cin >> num_of_vertices;
  11.    
  12.     int num_of_edges;
  13.     cin >> num_of_edges;
  14.    
  15.    
  16.     for(int i = 0; i < num_of_edges; i++) {
  17.         int a, b;
  18.         cin >> a >> b;
  19.         graph[a].push_back(b); // one directioanl
  20.         graph[b].push_back(a); // two directioanal
  21.     }
  22.     int S, E;
  23.     cin >> S >> E;
  24.     queue<int> q;
  25.    
  26.     q.push(S);
  27.     q.push(0);
  28.    
  29.     vector<bool> visited(num_of_vertices + 1, false);
  30.     while(!q.empty()) {
  31.         int node = q.front();
  32.         q.pop();
  33.         int dist = q.front();
  34.         q.pop();
  35.        
  36.         if(node == E) {
  37.             cout << dist << endl;
  38.             break;
  39.         }
  40.         for(int i = 0; i < (int) graph[node].size(); i++) {
  41.             int neighbour = graph[node][i];
  42.             if(!visited[neighbour]) {
  43.                 visited[neighbour] = true;
  44.                 q.push(neighbour);
  45.                 q.push(dist + 1);
  46.             }
  47.         }
  48.        
  49.     }
  50.  
  51.     return 0;
  52. }
  53.  
  54.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement