Shortest Path in a Graph
Completed
Read an undirected graph (n nodes 1..n, m edges) and two nodes s, t. Print the number of edges on the shortest path, or -1, using BFS on an adjacency list.
Input
n m, m lines u v, then s t.
Output
One integer.
Example
Input
6 6 1 2 2 3 3 4 1 5 5 4 4 6 1 6
Output
3
Editor
C++
Hints
BFS explores nodes in order of distance from s.
Solution explanation
An adjacency list (vector of vectors) is the usual way to store sparse graphs.
Show solution
#include <iostream>
#include <queue>
#include <vector>
using namespace std;
int main() {
int n, m;
cin >> n >> m;
vector<vector<int>> adj(n + 1);
for (int i = 0; i < m; i++) {
int u, v;
cin >> u >> v;
adj[u].push_back(v);
adj[v].push_back(u);
}
int s, t;
cin >> s >> t;
vector<int> dist(n + 1, -1);
queue<int> q;
dist[s] = 0;
q.push(s);
while (!q.empty()) {
int u = q.front();
q.pop();
for (int v : adj[u]) {
if (dist[v] == -1) {
dist[v] = dist[u] + 1;
q.push(v);
}
}
}
cout << dist[t] << "\n";
return 0;
}