Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- #include <queue>
- using namespace std;
- const int maxn = 1e5 + 5;
- int n, m;
- vector<int> graph[maxn];
- void bfs(int S, int E) {
- queue<int> q;
- q.push(S);
- q.push(0);
- vector<bool> visited(n + 1, false);
- visited[S] = true;
- while(!q.empty()) {
- int node = q.front();
- q.pop();
- int dist = q.front();
- q.pop();
- if(node == E) {
- cout << dist << endl;
- break;
- }
- for(int neighbour : graph[node]) {
- if(!visited[neighbour]) {
- visited[neighbour] = true;
- q.push(neighbour);
- q.push(dist + 1);
- }
- }
- }
- }
- int main() {
- ios_base::sync_with_stdio(false);
- cin >> n >> m;
- for(int i = 0; i < m; i++) {
- int a, b;
- cin >> a >> b;
- graph[a].push_back(b);
- graph[b].push_back(a);
- }
- int S, E;
- cin >> S >> E;
- bfs(S, E);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment