#C3906. Shortest Path in a Maze

    ID: 47385 Type: Default 1000ms 256MiB

Shortest Path in a Maze

Shortest Path in a Maze

You are given a maze represented as an undirected graph with n nodes and m edges. Each edge connects two nodes. Your task is to determine the shortest path from a starting node s to a target node t. The length of the path is defined as the number of edges traversed. If there is no valid path between s and t, output -1.

You can solve this problem using the Breadth-First Search (BFS) algorithm. This algorithm efficiently finds the shortest path in an unweighted graph. Note that if the starting node is the same as the target node, the shortest path length is 0.

Input and Output through Standard Streams: The solution must read input from standard input (stdin) and produce output to standard output (stdout).

inputFormat

The input is provided via standard input (stdin) in the following format:

  1. The first line contains two space-separated integers n and m, representing the number of nodes and edges respectively.
  2. The next m lines each contain two space-separated integers u and v, representing an undirected edge between nodes u and v.
  3. The last line contains two space-separated integers s and t, denoting the starting node and the target node respectively.

outputFormat

Output a single integer to standard output (stdout): the length of the shortest path from node s to node t. If no such path exists, output -1.## sample

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

</p>