Channel
Time limit3sMemory limit256 MB
Find the longest path from the top-left to the bottom-right dirt cell in a grid of rocks, where the path never touches itself, not even diagonally.
- Level
Medium7 of 10
- Topics
- Backtracking, DFS, Brute force
- Solved
- No attempts yet
Problem
Joe, a former champion coder, has finally bought the farm. No, he is alive and well. He used his programming competition winnings to buy his ancestral farm. He hopes to retire and spend the rest of his days tending cows. For some reason, he now considers himself an expert on cows.
Sadly, his plans will not work out. The farm sits in a cold northern climate, too cold for cows. The land is also dry and poor for growing crops. Joe realizes he must build an irrigation scheme for his field. The scheme diverts part of a river into a long, winding channel through the field. Crops nearest the channel will thrive, so the longer the channel, the better.
The field is a long rectangular strip divided into unit squares. Each square is either dirt, marked '.', or an immovable rock, marked '#'. The channel is one square wide. It enters at the upper left corner and exits at the lower right corner. The channel cannot pass through rocks. The channel must never touch itself, even at a corner, or the water will seep through and take a shortcut. Figure 3 and Figure 4 show examples of the channel touching itself.

Joe's best programming days are long behind him. His straightforward solution is far too slow. Can you help him find the optimal placement of this channel?
Input
The input consists of several test cases, at most 20. Each test case starts with a line containing , the number of rows (), and , the number of columns (). The next lines each contain a string of length describing the field. The last test case is followed by a line containing two zeros.
Output
For each test case, print the case number in the form Case 1:, then print lines showing the longest possible channel placement. Use 'C' for the channel. There is always a unique solution. Follow the format of the sample output. Print a blank line after the output of each test case.