Portal Game
InterviewTime limit1sMemory limit1024 MB
Find the minimum time to walk from cell 0 to cell N-1 when red portals must be taken and blue portals are optional, or report -1 if unreachable.
- Level
Medium4 of 10
- Topics
- Shortest path, Graph
- Solved
- No attempts yet
Problem
Portal Game is played on a straight line. The line has cells numbered from to . The goal is to start at cell and reach cell as quickly as possible.
The game has portals in total, and each portal is either red or blue. Each cell can hold at most one portal entrance. Using the portal whose entrance is at cell moves you to its exit at cell . Portals only work from entrance to exit, so you cannot use the same portal to go from back to .
Before reaching cell , you can take the following actions depending on the type of cell:
- A cell with no portal entrance: move from the current cell to cell , which takes 1 second.
- A cell with a red portal entrance: use the red portal to move to its exit in 0 seconds.
- A cell with a blue portal entrance: use the blue portal to move to its exit in 0 seconds, or move from cell to cell , which takes 1 second.
Input
The first line contains the number of cells and the number of portals , separated by a space. (, )
Each of the next lines describes one portal. Each line contains three integers , , and , separated by spaces. is the type of the -th portal: means red, and means blue. and are the cell numbers of the entrance and exit of the -th portal. (, , )
No two portals share an entrance. That is, if , then .
Output
Print the minimum time needed to start at cell and reach cell on the first line.
If no sequence of moves reaches cell , print .