#include #include #include #include #include #include #include #include #include #include #include using namespace std; typedef long long ll; struct Node { int y; int x; char ch; Node(int y = -1, int x = -1, char ch = -1) { this->y = y; this->x = x; this->ch = ch; } bool operator>(const Node &n) const { return ch > n.ch; } }; int main() { int H, W; cin >> H >> W; vector S(H); for (int y = 0; y < H; ++y) { cin >> S[y]; } queue que; que.push(Node(0, 0, S[0][0])); int history[H][W]; memset(history, -1, sizeof(history)); string ans = ""; ans += S[0][0]; bool visited[H][W]; memset(visited, false, sizeof(visited)); for (int i = 0; i < H + W - 2; ++i) { priority_queue , greater> pque; while (not que.empty()) { Node node = que.front(); que.pop(); if (node.y + 1 < H) { pque.push(Node(node.y + 1, node.x, S[node.y + 1][node.x])); } if (node.x + 1 < W) { pque.push(Node(node.y, node.x + 1, S[node.y][node.x + 1])); } } char ch = pque.top().ch; ans += ch; while (not pque.empty()) { Node node = pque.top(); pque.pop(); if (node.ch > ch) break; if (visited[node.y][node.x]) continue; visited[node.y][node.x] = true; que.push(node); } } cout << ans << endl; return 0; }