Fantasmagorie
Time limit1sMemory limit512 MB
Find a sequence of single-pixel flips that turns the first black and white image into the second while keeping each color's region count fixed.
- Level
Hard9 of 10
- Topics
- Graph, Simulation, Implementation
- Solved
- No attempts yet
Story
Émile's dreams often feature people or animals who become distorted into others. Émile would like to show the enchanting world of his dreams to everybody by creating the very first animated cartoon, in black and white of course. After waking up, Émile only remembers the initial and final forms appearing in his dream, not the transformation itself, so he is asking you to reproduce these "morphings" by detailing the steps taken for transforming the first image into the second.
Image constraints
Émile's images respect three constraints. First, all pixels on the border of the image, meaning the leftmost and rightmost columns and the top and bottom rows, have the same color. Second, the image does not contain any square of the form
or
.
The third constraint is as follows. Subdivide the image into regions, which are the connected monochromatic areas of the image. That is, regions form the finest partition of the pixels such that any two adjacent pixels of the same color are in the same region. Two regions are adjacent if they contain adjacent pixels. In Émile's images, every region is adjacent to at most two other regions, and the region containing the border pixels is adjacent to at most one other region.
Morphing
You are given two black and white images of the same size . Your goal is to find a "morphing" that transforms the first image into the second one. A morphing from image to image is a sequence of images starting with and ending with such that:
- each image (except the first) can be obtained from the previous one by flipping one bit;
- each image respects the three constraints above;
- the number of regions of each color does not change during the morphing.
Input
The first line contains two space-separated integers and . Then come lines that describe the first image row by row, from top to bottom. Each line is composed of characters describing the row's pixels from left to right: the -th character is '.' if the -th pixel of the row is white, and '#' if it is black. Finally come lines that describe the second image in the same format.
Output
If no morphing exists, print the word "IMPOSSIBLE" on a single line. Otherwise, describe one possible morphing. If the -th image is obtained from the -th image by flipping the pixel in column and row (with and , where is the leftmost column and is the topmost row), the -th output line contains the pair .
Limits
- The first and last images are distinct.
- The output contains at most pixel flips.