Nearest Charger Map

medium bfs graphs shortest-paths 2000 ms · 256 MB

Nearest Charger Map

A warehouse runs a fleet of autonomous robots on a grid floor plan. Each robot needs to know, for its current cell, how many moves it takes to reach the nearest charging dock. Robots move one grid cell at a time, north/south/east/west (no diagonals), and cannot enter cells occupied by shelving.

You are given the floor plan as a grid of R rows and C columns. Each cell is one of:

  • . — open floor, a robot can stand here
  • # — a shelving unit (wall); no robot can ever occupy this cell
  • C — a charging dock; also open floor, and the source of distance 0

For every cell, output the minimum number of moves from that cell to the nearest C cell, moving only through ./C cells and never through #. Print -1 for every # cell, and also -1 for any . cell that no charging dock can reach (for example, a floor pocket completely sealed off by shelving).

Input

The first line contains two integers R and C (1 ≤ R, C; 1 ≤ R·C ≤ 10^6).

Each of the next R lines contains a string of exactly C characters, each one of ., #, or C, describing one row of the floor plan. There may be any number of charging docks, including zero.

Output

Print R lines, each with C integers separated by single spaces: the answer for every cell of that row, in the same left-to-right order as the input. A C cell's own answer is 0.

Notes

In the first example, the two docks are close enough that cell (2,0) (0-indexed row, column) can be reached in 2 steps from either one, while the two shelving cells print -1.

In the second example, shelving completely separates the bottom row from the dock in the top row, so every cell of the bottom row prints -1 even though it is open floor — it just can't be reached.

Example 1

Input

3 3
C.#
.#.
..C

Output

0 1 -1
1 -1 1
2 1 0

Example 2

Input

3 4
C..#
####
....

Output

0 1 2 -1
-1 -1 -1 -1
-1 -1 -1 -1

Hints · reveal one at a time if you're stuck

Hint 1

Each cell's answer is the shortest number of moves through open cells, and every move costs the same. This is a shortest-path problem on an unweighted graph, so think about which search finds these distances.

Hint 2

Instead of searching from each dock separately, start one breadth-first search with every dock already at distance 0. Never step into a # cell, and any floor cell that the search never reaches stays at -1.

report an issue Prefer your own editor? sooks prep 94 (CLI)
Sign in to run code

Run your code on the examples, or submit it against every test.