Intermediate0-1 BFS 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.
Grading tests
C++ Suggestion Library
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.
Test
Result
Points
Execution time
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 a directed graph with N vertices and M edges. You want to travel from vertex S to vertex T. You may traverse an edge in its original direction at no cost. You may also traverse an edge in the opposite direction, but doing so costs 1 reversal. Find the minimum number of reversals required to reach T from S. If T is unreachable even when reversals are allowed, output -1. Self-loops and repeated edges are allowed.
Input format
First line: N M. Next M lines: U V. Last line: S T.
Output format
Print the minimum number of reversals needed.
Constraints
1 ≤ N ≤ 100000
0 ≤ M ≤ 200000
1 ≤ U, V, S, T ≤ N
Sample input
4 3
1 2
3 2
3 4
1 4
Sample output
1
Sample explanation
Travel 1 → 2 at cost 0, traverse the original edge 3 → 2 backwards at cost 1, then travel 3 → 4 at cost 0.
Need a hint?
For every directed edge U → V: - Add U → V with cost 0. - Add V → U with cost 1. Then run 0-1 BFS. Expected complexity: O(N + M).