Robots
Time limit2sMemory limit1024 MB
On a wrapping board with left and right turn fields, find the fewest turns for a robot to get from a start cell to a goal cell for each query, or -1 if impossible.
- Level
Hard9 of 10
- Topics
- Graph, Shortest path, Implementation
- Solved
- No attempts yet
Problem
Kile, a board game enthusiast, recently discovered the game Robots. The game uses a board with rows and columns and one robot. The field is the top-left field of the board, and the field is the bottom-right field.
At the start, the robot is placed on a field (-th row, -th column). The player can direct it in one of four directions: up, down, left, or right. The robot moves in the chosen direction until it reaches the goal or a special field. If it tries to leave the board, it wraps around to the opposite side. For example, if the robot is at and moves down, it arrives at .
The board has three types of fields:
- Empty field: the robot keeps moving in the same direction.
- Left turn field: when the robot steps on it, the robot turns left by 90° and keeps moving.
- Right turn field: when the robot steps on it, the robot turns right by 90° and keeps moving.
Most fields are empty. Only fields are left or right turn fields.
The game has rounds. In round , the robot is placed on . The goal is to reach with the minimum number of turns, or determine that it is impossible.
Note: If the robot starts or finishes on a left or right turn field, that turn is not counted.
Input
The first line contains integers , , and (, ), the number of rows, the number of columns, and the number of non-empty fields on the board.
Each of the following lines contains integers , and a character (, , is L or R). The pair is the row and column of the -th turn field, and is its type. L is a left turn field and R is a right turn field.
The next line contains an integer (), the number of rounds.
Each of the following lines contains integers , , , (, ), the start and the goal of the round.
Output
For each round, output the minimum number of turns on its own line, or -1 if the goal cannot be reached.