Jelly Raid

Guide the child from the bed to the fridge in the fewest turns while dodging patrols that catch anything sharing a clear row or column.

Medium7BFSSimulationShortest pathMathNo attempts yetTime limit1sMemory limit256 MB

Problem

The boarders at Adephagia School For Boys have a thin time of it after dinner. Savings have cut pudding down to a single biscuit, while the masters finish every meal with raspberry jelly. A custard cream or a bourbon is not a bad biscuit, but the children want the jelly, so they have planned a midnight raid.

One child has to get from a bed in the dormitory across the school to the fridge in the kitchen without being seen by the patrolling masters.

The school is a grid of rr rows and cc columns, and every cell is either walkable or blocked. Time runs in turns numbered from 00. On turn 00 the child stands on the bed and every master stands on the first coordinate of its route.

On each later turn the child either stays where it is or steps to a walkable cell that shares an edge with the current one. At the same time every master takes one step along its route. A master walks its route from the first coordinate to the last, then turns around and walks back to the first, and repeats that forever. A master whose route holds a single coordinate never moves.

A master looks along its own row and its own column. The child is caught if at the end of a turn the child and some master share a row or a column and every cell strictly between them is walkable. A master standing on the child's own cell also catches the child. One master never blocks the view of another, only a blocked cell does. The same check applies on turn 00.

The raid ends the moment the child stands on the fridge. Being seen on that same turn does not matter, because the child either sneaks back to bed unseen or gets caught full of jelly and does not care. The first sample case works out that way: the child reaches the fridge on turn 26 and a master spots it right then.

Input

The first line has two integers rr and cc (1<r,c601 < r, c \le 60), the number of rows and the number of columns.

The second line has two coordinates, the bed in the dormitory first and the fridge in the kitchen second. A coordinate is a row number and a column number inside parentheses, for example (2 5).

Each of the next rr lines has cc characters:

  • . walkable area
  • # blocked area

The next line has one integer pp (1p2001 \le p \le 200), the number of patrolling masters.

Each of the next pp lines describes one patrol route: an integer kk (1k71 \le k \le 7) followed by kk coordinates. Two coordinates next to each other on a route are equal or share an edge.

The bed, the fridge and every route coordinate are walkable.

Output

Print the minimum number of turns the child needs to reach the fridge. If the child cannot reach the fridge, print IMPOSSIBLE.