Advertisement
Josif_tepe

Untitled

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