Magical Maze
Time limit1.5sMemory limit512 MB
Count ordered pairs of chambers (x, y) that both lie on some path from the entrance to the exit of a one-way grid maze, where y is reachable from x.
- Level
Hard8 of 10
- Topics
- Graph, Dynamic programming, Topological sort
- Solved
- No attempts yet
Problem
Maggy's class went on an excursion to a maze. The maze is a rectangle meters high and meters wide, made of square chambers of size meter each. Between any two chambers that share a side there is a one-directional passage. Some passages are closed for repairs. It is not even known whether the exit can be reached from the entrance.
Before entering, Maggy gets a map that shows the direction of each passage and which passages are closed. The entrance is the upper left chamber, and the only exit is the bottom right chamber. The map also guarantees that you cannot loop forever in the maze: if you leave any chamber through any passage, you cannot get back to that chamber.
Maggy wants to start at the entrance, go through the maze, and leave through the exit. She also writes down the numbers of two favourite chambers she visited, in the order she visited them. One chamber may be written twice. If Maggy fails to leave the maze, she is upset and writes nothing. Given the map, count the number of different ways Maggy can write down the two numbers.
Input
The first line contains two integers and separated by a single space (). The following lines contain the map of the maze.
The -th line () is a string of characters from the set {>, <, *}, describing the passages between consecutive chambers in the -th row. If the -th character is >, there is a passage from the -th to the -st chamber in that row. < means there is a passage from the -st to the -th chamber. * means there is no passage between them in either direction.
The -th line () is a string of characters from the set {v, ^, *}, describing the passages between the -th and -st rows. If the -th character is v, there is a passage from the -th chamber in the -th row to the -th chamber in the -st row. ^ means the passage goes the other way. * means there is no passage in either direction.
The entrance is the first chamber in the first row, and the exit is the last chamber in the last row.
Output
Print one integer: the number of ways Maggy can write down the numbers of two visited chambers, in the order of visiting them. If the exit cannot be reached, print 0.
Hint
There is only one way to reach the exit: first go right twice, then go down once.