Untitled

mail@pastecode.io avatar
unknown
c_cpp
3 years ago
1.1 kB
0
Indexable
Never
#include <iostream>
#include <vector>
#include <algorithm>
#include <queue>
using namespace std;
vector<int> graph[100005];
int main(){
    ios_base::sync_with_stdio(false);
    int n, m;
    cin >> n >> m;
    for(int i = 0; i < m; i++) {
        int a, b;
        cin >> a >> b;
        graph[a].push_back(b); // bidirectional graph
        graph[b].push_back(a);
    }
    int S, E; // Start, End
    cin >> S >> E;
    vector<bool> visited(n + 1, false);
    visited[S] = true;
    queue<int> q;
    q.push(S);
    q.push(0);
    while(!q.empty()) {
        int vertex = q.front();
        q.pop();
        int dist = q.front();
        q.pop();
        if(vertex == E) {
            cout << dist << endl;
            break;
        }
        for(int i = 0; i < graph[vertex].size(); i++) {
            int neighbours = graph[vertex][i];
            if(!visited[neighbours]) {
                visited[neighbours] = true;
                q.push(neighbours);
                q.push(dist + 1);
            }
        }
        
    }
    
    return 0;
}