package main import ( "bufio" "fmt" "os" "strconv" ) var sc = bufio.NewScanner(os.Stdin) var out = bufio.NewWriter(os.Stdout) func main() { buf := make([]byte, 1024*1024) sc.Buffer(buf, bufio.MaxScanTokenSize) sc.Split(bufio.ScanWords) h, w := nextInt(), nextInt() s := make([]string, h) for i := 0; i < h; i++ { s[i] = nextString() } ans := solve(h, w, s) PrintString(ans) } func solve(h, w int, s []string) string { const INF = 1 << 60 dp := make([][]int, h) for i := 0; i < h; i++ { dp[i] = make([]int, w) for j := 0; j < w; j++ { dp[i][j] = INF } } dp[0][0] = int(s[0][0]) for i := 1; i < h; i++ { dp[i][0] = Min(dp[i][0], dp[i-1][0]+int(s[i][0])) } for j := 1; j < w; j++ { dp[0][j] = Min(dp[0][j], dp[0][j-1]+int(s[0][j])) } for i := 1; i < h; i++ { for j := 1; j < w; j++ { dp[i][j] = Min(dp[i-1][j], dp[i][j-1]) dp[i][j] += int(s[i][j]) } } var reversed []string i, j := h-1, w-1 for { reversed = append(reversed, string(s[i][j])) if i == 0 && j == 0 { break } if i > 0 && dp[i-1][j] == dp[i][j]-int(s[i][j]) { i-- } else if j > 0 && dp[i][j-1] == dp[i][j]-int(s[i][j]) { j-- } } var ans string for i := len(reversed) - 1; i >= 0; i-- { ans += reversed[i] } return ans } func nextInt() int { sc.Scan() i, _ := strconv.Atoi(sc.Text()) return i } func nextString() string { sc.Scan() return sc.Text() } func PrintString(x string) { defer out.Flush() fmt.Fprintln(out, x) } func Min(x, y int) int { if x < y { return x } return y }