This page is still under construction.

Parts of this page are still being built. What you see may change.

Laser Communication

Interview

Time limit1sMemory limit128 MB

Summary
On a grid with walls and two C cells, find the fewest mirrors (/ or \) needed so a laser fired from one C reaches the other.
Level

Medium6 of 10

Topics
BFS, Graph, Shortest path, Implementation
Solved
No attempts yet

Problem

There is a W×HW \times H map divided into 1×11 \times 1 square cells. Each cell is either empty or a wall, and exactly two of the cells are marked with the letter C.

You want to connect the two cells marked C with a laser. A laser is fired from a C cell in one of the four directions (up, down, left, or right). By placing a mirror / or \ on an empty cell, you can turn the laser's direction by 90 degrees at that cell. A laser cannot pass through a wall cell.

Write a program that finds the minimum number of mirrors that must be placed so that the two C cells are connected by a laser.

The figure below shows an example with H=8H = 8 and W=7W = 7, where empty cells are drawn as . and walls as *. The left side is the initial state, and the right side shows the two C cells connected using the minimum number of mirrors.

7 . . . . . . .         7 . . . . . . .
6 . . . . . . C         6 . . . . . /-C
5 . . . . . . *         5 . . . . . | *
4 * * * * * . *         4 * * * * * | *
3 . . . . * . .         3 . . . . * | .
2 . . . . * . .         2 . . . . * | .
1 . C . . * . .         1 . C . . * | .
0 . . . . . . .         0 . \-------/ .
  0 1 2 3 4 5 6           0 1 2 3 4 5 6

Input

The first line contains the map's width WW and height HH. (1≤W,H≤1001 \le W, H \le 100)

From the second line, the map is given over HH lines, each consisting of WW characters. The characters mean:

  • .: an empty cell
  • *: a wall
  • C: a cell that must be connected by the laser

There are always exactly two C cells, and only inputs in which the two cells can be connected by a laser are given.

Output

On the first line, print the minimum number of mirrors that must be placed to connect the two C cells.

Examples3

  1. Example 1

    Input
    7 8
    .......
    ......C
    ......*
    *****.*
    ....*..
    ....*..
    .C..*..
    .......
    
    Expected output
    3
    
  2. Example 2

    Input
    2 1
    CC
    
    Expected output
    0
    
  3. Example 3

    Input
    3 3
    C..
    ...
    ..C
    
    Expected output
    1