import std; struct Grid { int x, y; int opCmp(Grid that) { if (this.x != that.x) { if (this.x > that.x) return 1; else return -1; } if (this.y != that.y) { if (this.y > that.y) return 1; else return -1; } return 0; } } void main() { int H, W; readf("%d %d\n", H, W); auto S = new string[](H); foreach (i; 0 .. H) readf("%s\n", S[i]); auto mn = new string[](H+W); mn[1] = S[0][0].to!string; foreach (i; 2 .. H+W) mn[i] = "{"; Grid[] list; list ~= Grid(0, 0); foreach (i; 2 .. H+W) { bool[Grid] nxt; foreach (l; list) { if (l.x + 1 < H) { string T = mn[i-1] ~ S[l.x+1][l.y]; if (T < mn[i]) { nxt.clear; nxt[Grid(l.x+1, l.y)] = true; mn[i] = T; } else if (T == mn[i]) { nxt[Grid(l.x+1, l.y)] = true; } } if (l.y + 1 < W) { string T = mn[i-1] ~ S[l.x][l.y+1]; if (T < mn[i]) { nxt.clear; nxt[Grid(l.x, l.y+1)] = true; mn[i] = T; } else if (T == mn[i]) { nxt[Grid(l.x, l.y+1)] = true; } } } list = nxt.keys; } string res = mn.back; res.writeln; }