cppAcademy
← Back to the DFS lesson

Find a Path

IntermediateDFS 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. Find a Path accepts any valid path. 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 recursive DFS can overflow the WASM stack; an explicit stack is safer for long paths.

Problem statement

Given an undirected graph with vertices numbered from 1 to N and two vertices S and T, find any path from S to T. A path must not repeat a vertex. It does not have to be the shortest path. Self-loops and repeated edges may appear in the input. If S equals T, the one-vertex path is valid.

Input format

The first line contains N and M. The next M lines contain the endpoints U and V of each edge. The last line contains S and T.

Output format

If no path exists, print IMPOSSIBLE on its own line. Otherwise, print the number K of vertices on the first line and the K vertex numbers in order on the second line. Different valid paths are accepted.

Constraints

  • 1 ≤ N ≤ 100000
  • 0 ≤ M ≤ 200000
  • 1 ≤ U, V, S, T ≤ N
  • 1 ≤ K ≤ N; no repeated vertices in the output path

Sample input

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

Sample output

4
1 2 3 4

Sample explanation

The edges 1–2, 2–3 and 3–4 form a path from 1 to 4. Store each vertex's parent when it is first discovered, then reconstruct the path backwards from T.

Need a hint?

Mark vertices when discovering them, record their parents, and follow the parent chain from T back to S. Reverse that chain before printing.

Review Depth-first search →