Easy Shortest Distance
Time limit1sMemory limit128 MB
Given a grid with one target cell and blocked cells, find the shortest distance from each open cell to the target using 4-directional moves.
Problem
You are given a map. For every cell, find the shortest distance to the target cell.
To keep the problem easy, you may move only up, down, left, and right. One move to an adjacent cell adds 1 to the distance, and blocked land cannot be entered.
Input
The first line contains the map size and , where is the height and is the width. (, )
Each of the next lines contains numbers separated by spaces. 0 is blocked land, 1 is open land, and 2 is the target cell. Exactly one 2 appears in the whole input.
Output
Print lines with numbers each, separated by spaces. The -th number on the -th line is the shortest distance from the cell in row , column to the target cell.
Print 0 for a cell of blocked land. Print -1 for a cell of open land that cannot reach the target cell. The target cell itself prints 0.