The Right-Turn Drivers' Club
InterviewTime limit1sMemory limit128 MB
On a grid with blocked cells, find the shortest A-to-B path that never turns left or makes a U-turn, counting squares visited.
- Level
Medium6 of 10
- Topics
- BFS, Graph, Matrix, Shortest path
- Solved
- No attempts yet
Problem
We are given a rectangular city map made of unit squares, where and . The rows are numbered from to from top to bottom, and the columns from to from left to right. Every square is either free or blocked, and traffic is allowed only on free squares.
From a free square you may move to a free square adjacent to it (one that shares a side). You may never immediately turn back, that is, you may not return to the square you have just left (no U-turn). You may also never make a left turn: after each move you may only keep going straight or turn right, relative to your current direction of travel. The very first move out of the start square may point in any of the four directions, because there is no previous direction yet.
The length of a route is the number of squares it passes through, counting both endpoints; a square may be counted more than once if the route visits it more than once.
You are given two different squares and . Decide whether it is possible to drive from to without any left turn, and if it is, report the minimum possible length of such a route. If or is blocked, no route exists.
Input
The first line contains two integers and separated by a single space.
Each of the next lines contains a string of length made of the digits and that describes one row of the map: marks a free square and marks a blocked square.
The next line contains two integers, the row and the column of square . The following line contains, in the same format, the row and the column of square . Squares and are different. The input is always well-formed and you do not need to validate it.
Output
Print a single line.
If there is no route from to without a left turn, or if or is blocked, print the single word NIE (Polish for "no").
Otherwise print one integer: the minimum length of a route from to that makes no left turn, that is, the number of squares it passes through, counting both and .