Tetris Alphabet
Time limit1sMemory limit128 MB
Given the final well of a Tetris game with lettered pieces, find the lexicographically smallest order in which the pieces could have landed.
- Level
Medium7 of 10
- Topics
- Graph, Topological sort, Greedy, Implementation
- Solved
- No attempts yet
Problem
Tetris is played in a well that has rows and columns. Figures fall straight down into the well one at a time; each figure is a set of cells that is connected through shared edges (up, down, left, right). When a figure falls it keeps dropping until at least one of its cells lands on the floor or on top of a cell that is already occupied.
After every figure has landed, each one is marked with a distinct uppercase letter from A to Z. Given the final contents of the well, reconstruct an order in which the figures could have fallen.
A figure could have been the most recent one to land only if it can be lifted straight up out of the well without passing through any other figure — that is, no other figure occupies a cell directly above one of its cells in the same column. Removing figures this way, from the last one to the first, recovers a valid falling order.
Input
The first line contains an integer (), the number of rows.
Each of the next lines contains exactly characters. Every character is either an uppercase letter from A to Z, marking a cell that belongs to a figure, or a dot . (ASCII ), marking an empty cell.
Output
Print a single line containing the letters of the figures in the order they fell. If more than one order is possible, print the lexicographically smallest one. The input guarantees that at least one valid order exists.