Lexicographically Smallest PathMedium

Lexicographically Smallest Path

MediumPractice library · +20 XPrecursiondynamic programminggraphs

Given a grid of characters, find the lexicographically smallest path from the top-left cell (0,0) to the bottom-right cell (R-1, C-1). You can only move right or down. The path is represented by the sequence of characters visited, starting from the top-left and ending at the bottom-right. If multiple paths have the same lexicographically smallest sequence, choose the one with the minimum length (though all paths will have the same length R+C-1 in this problem).

Input

The first line contains two integers R and C (1 <= R, C <= 200). The next R lines each contain C characters, representing the grid.

Output

Print the lexicographically smallest path as a string.

Constraints

1 <= R, C <= 200. Grid contains only lowercase English letters.

Time limit 2 s (native code; slower languages get more)Memory 256 MB15 hidden tests

Example 1

Input
3 3
abc
def
ghi
Output
abcfi

The path 'adg' is lexicographically smaller than 'abe', 'abf', etc. The path 'adg' leads to 'adg'. The path 'aei' leads to 'aei'. The path 'abdh' leads to 'abdh'. The path 'abdg' leads to 'abdg'. The path 'adg' is indeed the smallest.

Example 2

Input
2 4
xzyw
aqrs
Output
xaqrs

The path 'xaqrs' is smaller than 'xzyrs'.

Hints