Traffic Lanes
InterviewTime limit1sMemory limit128 MB
Find the fewest lane changes needed to drive across an n by m grid of blocked and free cells, starting and ending in any lane.
- Level
Medium5 of 10
- Topics
- Shortest path, BFS, Matrix
- Solved
- No attempts yet
Problem
Long ago, a highway with lanes was built in Bytocia (Bajtocja), connecting the two cities and . The road became so heavily travelled that some of its fragments turned impassable.
Bajtek, a resident of city , does not like turning the steering wheel too many times. He wonders how to reach city while changing lanes as few times as possible.
Bajtek may start his journey from any lane and may also finish on any lane. Under the highway traffic rules, making a U-turn or reversing is not allowed.
Input
The first line of standard input contains two integers and (). Each of the next lines describes one lane, in order. Each such line contains integers: 0 marks a passable fragment of the highway and 1 marks an impassable one.
Output
Print a single integer, the minimum number of lane changes, on the first and only line of standard output. If crossing the highway is impossible, print the single word NIE instead.