Tetris Alphabet

Time limit1sMemory limit128 MB

Summary
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 NN rows and 2020 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 NN (1≤N≤501 \le N \le 50), the number of rows.

Each of the next NN lines contains exactly 2020 characters. Every character is either an uppercase letter from A to Z, marking a cell that belongs to a figure, or a dot . (ASCII 4646), 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.

Examples3

  1. Example 1

    Input
    6
    ...........XX.......
    ..........MMMM......
    ..........K.........
    ........KKK.........
    .....ZAAA.FFF.......
    .....ZZZA..F.B......
    
    Expected output
    BFZAKMX
    
  2. Example 2

    Input
    2
    BBBB................
    AAAA................
    
    Expected output
    AB
    
  3. Example 3

    Input
    1
    A....B....C.........
    
    Expected output
    ABC