Laser Communication
InterviewTime limit1sMemory limit128 MB
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 map divided into 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 and , 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 and height . ()
From the second line, the map is given over lines, each consisting of characters. The characters mean:
.: an empty cell*: a wallC: 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.