Crosswords Insider
Time limit1sMemory limit128 MB
Given a list of words and a crossword grid template, decide whether each word can fill one run of empty cells and output the lexicographically smallest filled grid.
- Level
Hard8 of 10
- Topics
- Backtracking, Simulation, String matching, Greedy
- Solved
- No attempts yet
Problem
You have an insider at a newspaper who sends you the list of answer words for its crossword puzzle. Unfortunately the list does not tell you which word goes where, and although it is usually correct it may occasionally contain errors or omissions. Given the list of words and the shape of the crossword grid, determine whether every word can be placed into the grid so that the whole puzzle is filled, and if so output the completed grid.
Input
The input contains one or more problem sets.
Each problem set begins with a line containing two integers and . A line with and marks the end of the input and must not be processed. is the number of words to place and satisfies . is the number of rows in the grid and satisfies .
The next lines each contain one word, left-justified. Every word consists only of alphabetic characters, has length between and , and no word is repeated within a problem set.
The next lines describe the grid template, left-justified, using only the characters . and #. All template lines have the same length, which is between and . A . marks a cell where a letter may be written; a # marks a cell where no letter may appear.
Output
Each word must be placed either horizontally (left to right) or vertically (top to bottom) so that it exactly fills one maximal straight run of . cells: every . cell must be covered and no # cell may be used. A horizontal word and a vertical word may cross at a shared cell, but two horizontal words (or two vertical words) may never touch or overlap without at least one # between them. Each word from the list is used exactly once.
For each problem set, first output Problem followed by the problem set number (numbered from in the order they appear).
- If no valid placement exists, append
: No layout is possible.on the same line. - Otherwise, on the following lines, output the completed grid: the template with every
.replaced by the letter placed there, keeping every#unchanged. If more than one valid placement exists, output the lexicographically smallest completed grid. Compare two grids by reading all rows top to bottom and, within each row, left to right (including the#characters), and take the smaller sequence.