Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <cmath>
- #include <vector>
- #include <queue>
- using namespace std;
- typedef long long ll;
- const int maxn = 1e5 + 10;
- vector<int> graph[maxn];
- int n, m;
- int bfs(int S, int E) {
- queue<int> q;
- q.push(S); // current node
- q.push(0); // shortest distance from starting node to current node
- vector<bool> visited(n + 1, false);
- visited[S] = true;
- while(!q.empty()) {
- int current_node = q.front(); q.pop();
- int shortest_distance_from_start_till_now = q.front(); q.pop();
- if(current_node == E) {
- return shortest_distance_from_start_till_now;
- }
- for(int i = 0; i < (int) graph[current_node].size(); ++i) {
- int neighbour = graph[current_node][i];
- if(!visited[neighbour]) {
- visited[neighbour] = true;
- q.push(neighbour);
- q.push(shortest_distance_from_start_till_now + 1);
- }
- }
- }
- return -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);
- //undirected graph
- }
- int start, end;
- cin >> start >> end;
- cout << bfs(start, end) << endl;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment