Cows on Skates
InterviewTime limit1sMemory limit128 MB
Find a shortest orthogonal path from (1,1) to (R,C) through open grid cells, breaking ties by the lexicographically smallest sequence of cells.
- Level
Medium5 of 10
- Topics
- BFS, Graph, Matrix, Shortest path
- Solved
- No attempts yet
Problem
After years of pleading, Farmer John finally gave in and bought roller skates for the entire herd of cows. Much of the farm is perfect for roller-skating, but a few squares have far too many rocks and cannot be crossed on skates.
The farm is represented as a grid with rows and columns (, ). Around feeding time, Bessie finds herself at square and wants to get back to the barn at square . She may skate only between orthogonally adjacent squares (sharing an edge, never diagonally) that do not contain rocks. It is guaranteed that at least one such route from to exists.
Here denotes the square in row and column , with rows numbered from at the top and columns from at the left.
Input
- Line 1: two space-separated integers and .
- Lines : each line contains characters with no spaces. Each character is either '.', meaning Bessie can skate on that square, or '*', meaning the square has too many rocks. The -th character of the -th of these lines describes square . Squares and are always '.'.
Output
Output the shortest path from to . A path is a sequence of squares that starts at and ends at , in which consecutive squares are orthogonally adjacent (sharing an edge) and no square is a rock. The shortest path is the one containing the fewest squares.
If several shortest paths exist, output the lexicographically smallest one. Compare the two paths as sequences of squares from the beginning; each square is treated as the pair and pairs are compared by row first, then by column.
Print the squares of the path one per line, each as two space-separated integers 'row col'. The first line must be '1 1' and the last line must be 'R C' (that is, and ).