Paint by Numbers
Time limit1sMemory limit128 MB
Given the run lengths of stars in every row and column of an n x m grid, reconstruct the lexicographically smallest grid of dots and stars.
- Level
Medium7 of 10
- Topics
- Backtracking, Implementation, Brute force, Greedy
- Solved
- No attempts yet
Problem
Long ago there was a craft known as paint-by-numbers: you were handed a line drawing with a number written inside each enclosed region, and each number told you which colour to use for that region. An example is shown below.

The puzzle you have to solve here is more linear, in a sense.
You are given an grid that you must "colour" so that every cell holds either a dot (.) or a star (*).
The grid is not described in the usual paint-by-numbers way — that would be too easy. Instead, you must deduce which cells are dots and which are stars from a set of number sequences: one sequence for every row and one for every column. Each sequence gives, in order, the length of every run of consecutive stars in that row or column. Two consecutive runs of stars must be separated by at least one dot.
An example is shown below (it is meant to look like a fish).

Some of these puzzles have more than one valid grid. When several grids satisfy all of the row and column sequences, output the lexicographically smallest one; the ordering is defined precisely in the Output section.
Input
The input consists of lines.
The first line contains the integer , the number of rows. The second line contains the integer , the number of columns.
The next lines describe the rows from top to bottom. Each line lists the lengths of the star runs in that row as space-separated positive integers and is terminated by a . A row that contains no stars is written as a single .
The following lines describe the columns from left to right, in the same format.
Output
Print the finished grid as lines of characters each, where every character is a dot (.) or a star (*).
When more than one grid satisfies every row and column sequence, print the lexicographically smallest one. To compare two grids, read their cells in row-major order — the top row first, and left to right within each row — and find the first position where the two grids differ. Treating a dot (.) as smaller than a star (*), the grid that has a dot at that position is the smaller one. Print that grid.