#include using namespace std; const int INF = 100000; int main(){ int H, W; cin >> H >> W; vector> S(H, vector(W)); for (int i = 0; i < H; i++){ for (int j = 0; j < W; j++){ cin >> S[i][j]; } } vector cnt(H + W - 1, 0); vector> x(H + W - 1), y(H + W - 1); vector> id(H, vector(W)); for (int i = 0; i < H; i++){ for (int j = 0; j < W; j++){ id[i][j] = cnt[i + j]; cnt[i + j]++; x[i + j].push_back(i); y[i + j].push_back(j); } } vector> dp(H + W - 1); vector> nxt(H + W - 1); for (int i = 0; i < H + W - 1; i++){ dp[i].resize(cnt[i]); nxt[i].resize(cnt[i]); } dp[H + W - 2][0] = 0; for (int i = H + W - 3; i >= 0; i--){ vector> P(cnt[i]); for (int j = 0; j < cnt[i]; j++){ int mn = INF; if (x[i][j] < H - 1){ mn = min(mn, dp[i + 1][id[x[i][j] + 1][y[i][j]]]); if (mn == dp[i + 1][id[x[i][j] + 1][y[i][j]]]){ nxt[i][j] = id[x[i][j] + 1][y[i][j]]; } } if (y[i][j] < W - 1){ mn = min(mn, dp[i + 1][id[x[i][j]][y[i][j] + 1]]); if (mn == dp[i + 1][id[x[i][j]][y[i][j] + 1]]){ nxt[i][j] = id[x[i][j]][y[i][j] + 1]; } } P[j] = make_pair(S[x[i][j]][y[i][j]], mn); } vector> P2 = P; sort(P2.begin(), P2.end()); P2.erase(unique(P2.begin(), P2.end()), P2.end()); for (int j = 0; j < cnt[i]; j++){ dp[i][j] = lower_bound(P2.begin(), P2.end(), P[j]) - P2.begin(); } } string ans; int p = 0; for (int i = 0; i < H + W - 1; i++){ ans += S[x[i][p]][y[i][p]]; if (i < H + W - 2){ p = nxt[i][p]; } } cout << ans << endl; }