summaryrefslogtreecommitdiffstats
path: root/03-algorithms_on_graphs/03-paths_in_graphs/01-bfs/bfs.cpp
blob: a4117898400fda9e2e986f04fb72578a1e49ac5c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#include <iostream>
#include <vector>
#include <queue>

using std::vector;
using std::queue;

int distance(vector<vector<int> > &adj, int s, int t) {
  vector<int> d(adj.size(), -1);

  queue<int> q;
  q.push(s);
  d[s] = 0;

  while (!q.empty()) {
      int v = q.front();
      q.pop();
      for (int i = 0; i < adj[v].size(); i++) {
          int w = adj[v][i];
          if (d[w] == -1) {
              q.push(w);
              d[w] = d[v] + 1;
          }
      }
  }
  return d[t];
}

int main() {
  int n, m;
  std::cin >> n >> m;
  vector<vector<int> > adj(n, vector<int>());
  for (int i = 0; i < m; i++) {
    int x, y;
    std::cin >> x >> y;
    adj[x - 1].push_back(y - 1);
    adj[y - 1].push_back(x - 1);
  }
  int s, t;
  std::cin >> s >> t;
  s--, t--;
  std::cout << distance(adj, s, t) << '\n';
}