Under construction

Still being built. Things may change

Traffic Lanes

Interview

Time limit1sMemory limit128 MB

Summary
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 nn lanes was built in Bytocia (Bajtocja), connecting the two cities AA and BB. The road became so heavily travelled that some of its fragments turned impassable.

Bajtek, a resident of city AA, does not like turning the steering wheel too many times. He wonders how to reach city BB 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 nn and mm (1≤n,m≤10001 \le n, m \le 1000). Each of the next nn lines describes one lane, in order. Each such line contains mm 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.

Examples1

  1. Example 1

    Input
    4 5
    0 0 0 1 0
    0 1 0 1 0
    1 1 0 0 0
    0 0 1 0 1
    
    Expected output
    2