Possible First Tiles
Time limit1sMemory limit128 MB
Given a top view of 5x5 letter tiles on a grid, print NO when the view is impossible and otherwise list the tiles that could have been laid first.
- Level
Medium7 of 10
- Topics
- Topological sort, Brute force, Matrix
- Solved
- No attempts yet
Problem
You are given () square tiles of size . They are laid on an () square table one at a time, with their edges parallel to the edges of the table. Every tile lies completely inside the table, and a tile laid later can cover part of the tiles laid before it.
The tiles are named with consecutive letters starting from A, so 5 tiles are called A, B, C, D and E. The arrangement after the last tile is laid is written down as a top-view. A position that no tile covers is written as ., and every other position is written as the name of the tile that is on top there.
Here are four top-views of an table. Top-view 1 shows tile A laid after tile B.
Top-view 1
...........
..BBBBB....
..BBBBB....
..BBBBB....
..BBAAAAA..
..BBAAAAA..
....AAAAA..
....AAAAA..
....AAAAA..
...........
...........
Top-view 2
...........
..BBBBB....
..BBBBB....
..BBBBB....
..BBAAAAA..
..BBAAAAACC
DDDDAAAAACC
DDDDAAAAACC
DDDDAAAAACC
DDDDD.CCCCC
DDDDD......
Top-view 3
...........
...........
....AAAA...
...BAAAAB..
...BAAAAB..
...BAAAAB..
.CCCAAAAB..
.C.CCCCCB..
.CCCCCCC...
...........
...........
Top-view 4
...AAAAA...
...AAAAA...
...AAAAA...
...AAAAADDD
BBBBBAAADDD
BBBBB.DDDDD
BBBCCCDDDDD
BBBCCCDDDDD
BBBCCCCC...
...CCCCC...
...CCCCC...
When a top-view is valid, we can work out every tile that might have been the very first one laid on the table. In Top-view 2 the first tile could be B, C or D, but it could not be A.
A top-view is invalid for one of two reasons. The first is that some tile is not a square. Top-view 3 fails this way: A covers only 5 rows and 4 columns, B spans more than 5 columns, and C has a hole in it. Any one of these is enough to call the top-view invalid.
The second reason is that the tiles could not have been laid one after another. The four tiles in Top-view 4 interlock, so no order of laying them produces this picture, and the top-view is invalid.
Given a top-view, print NO if it is invalid. Otherwise print the names of the tiles that might have been laid first, in ascending order.
Input
The first line contains , the number of tiles. The second line contains , the side length of the table. Each of the next lines contains characters and describes one row of the top-view, from the top row down. Every character is either . or one of the uppercase letters starting from A.
Output
If the top-view is invalid, print NO. Otherwise print the names of the tiles that might have been laid first, in ascending order and with no spaces between them.