cppAcademy
← Back to the BFS lesson

Shortest Path Length

BeginnerBFS practice · C++17Best score: not submitted

Client-side educational grading. Submit runs your C++17 program against ten predefined tests in your browser. Tests are intentionally visible through See Hidden Tests. Scores are local practice records, not secure competition results.

main.cpp · C++17

Loading Monaco Editor…

Loading this problem’s draft…

Ctrl / ⌘ + Enter runs your custom test. Input limit: 1 MiB.

Loading editor…

Standard Output

Standard Error

Compiler Diagnostics

Submission results

Ten tests, ten points each. Output is checked against the expected answer. Custom runs never change your score.

Each test has a 5-second execution limit, 256 MiB linked program WASM memory maximum, and 1 MiB combined output limit. Allocated WASM memory is not peak browser memory. Deep recursion can overflow the WASM stack; an iterative traversal is safer for long paths.

Problem statement

You are given an undirected, unweighted graph with N vertices and M edges. Find the minimum number of edges required to travel from vertex S to vertex T. If T cannot be reached from S, output -1.

Input format

First line: N M. Next M lines: U V. Last line: S T.

Output format

Print one integer: the minimum number of edges from S to T, or -1 if no path exists.

Constraints

  • 1 ≤ N ≤ 100000
  • 0 ≤ M ≤ 200000
  • 1 ≤ U, V, S, T ≤ N
  • Self-loops and repeated edges are allowed.

Sample input

6 6
1 2
1 3
2 4
3 4
4 5
5 6
1 6

Sample output

4

Sample explanation

One shortest path is 1 → 2 → 4 → 5 → 6. It contains four edges.

Need a hint?

BFS with a distance array. Expected complexity: O(N + M).

Review BFS →