Problem:
The Secret Number Your job is to find out the secret number hidden in a matrix,
each of whose element is a digit ('0'-'9') or a letter
('A'-'Z').  You can see an example matrix in Figure 1.  Figure 1:  A Matrix The secret number and other non-secret ones are coded in a
matrix as sequences of digits in a decimal format.  You should
only consider sequences of digits D 1  D 2 ... D n such that D k +1 (1 <= k < n )
is either right next to or immediately below D k in the matrix.  The secret you are
seeking is the largest number coded in this manner. Four coded numbers in the matrix in Figure 1, i.e., 908820,
23140037, 23900037, and 9930, are depicted in Figure 2.  As you
may see, in general, two or more coded numbers may share a
common subsequence.  In this case, the secret number is
23900037, which is the largest among the set of all coded numbers
in the matrix.  Figure 2: Coded Numbers In contrast, the sequences illustrated in Figure 3 should be
excluded: 908A2 includes a letter; the fifth digit of 23149930
is above the fourth; the third digit of 90037 is below right of
the second.  Figure 3: Inappropriate Sequences Write a program to figure out the secret number from a given
matrix. Input The input consists of multiple data sets, each data set
representing a matrix.  The format of each data set is as
follows.  W  H  C 11 C 12 ... C 1 W  C 21 C 22 ... C 2 W ...  C H 1 C H 2 ... C HW  In the first line of a data set, two positive integers W and H are given. W indicates the width (the
number of columns) of the matrix, and H indicates the
height (the number of rows) of the matrix. W+H is less
than or equal to 70.  H lines follow the first line, each of which corresponds
to a row of the matrix in top to bottom order.  The i -th
row consists of W characters C i 1 C i 2 ... C iW in left to right order.  You may
assume that the matrix includes at least one non-zero digit. Following the last data set, two zeros in a line indicate the
end of the input. Output For each data set, print the secret number on a line.  Leading zeros
should be suppressed. Sample Input 7 4
9R2A993
0E314A0
8A900DE
820R037
6 7
JH03HE
ID7722
0DA1AH
30C9G5
99971A
CA7EAI
AHLBEM
20 2
A1234567891234CBDEGH
BDEDF908034265091499
0 0 Output for the Sample Input 23900037
771971
12345908034265091499

Solution (Python):



while True:
	W, H = map(int, input().split())
	if W == 0: break
	d = [list(input()) for r in range(H)]
	a = [[0 for c in range(W)] for r in range(H)]
	ans = 0
	for r in range(H):
		for c in range(W):
			if not d[r][c].isdigit(): continue
			a[r][c] = k = int(d[r][c])
			if c > 0 and d[r][c-1].isdigit():
				a[r][c] = a[r][c-1]*10 + k
			if r > 0 and d[r-1][c].isdigit():
				t = a[r-1][c]*10 + k
				a[r][c] = max(a[r][c], t)
			ans = max(ans, a[r][c])
	print(ans);

Solution (Python):



while True:
	W, H = map(int, input().split())
	if W == 0: break
	d = [list(input()) for r in range(H)]
	a = [[0 for c in range(W)] for r in range(H)]
	ans = 0
	for r in range(H):
		for c in range(W):
			if d[r][c] >= '0' and d[r][c] <= '9':
				k = int(d[r][c])
				k1 = k2 = 0
				if c > 0: k1 = a[r][c-1]*10 + k
				if r > 0: k2 = a[r-1][c]*10 + k
				a[r][c] = max(k, k1, k2)
				ans = max(ans, a[r][c])
	print(ans);

Solution (Python):
while 1:
	W, H = map(int,raw_input().split(" "))
	if W == H == 0: 
		break
	field = [[c for c in raw_input()] for _ in range(H)]
	secret = [0, ""]
	for j in range(H):
		for i in range(W):
			if not field[j][i].isdigit():
				continue
			pre = left = top = ""
			if i > 0 and field[j][i-1].isdigit() and field[j][i-1] != "0":
				left = field[j][i-1]
			if j > 0 and field[j-1][i].isdigit() and field[j-1][i] != "0":
				top = field[j-1][i]
			if len(left) == len(top):
				pre = left if left > top else top
			else :
				pre = left if len(left) > len(top) else top
			field[j][i] = pre + field[j][i]
			length = len(field[j][i])
			if length > secret[0]:
				secret[1] = field[j][i]
				secret[0] = length
			elif length == secret[0] and field[j][i] > secret[1]:
				secret[1] = field[j][i]
	print secret[1]

Solution (Python):
while 1:
	W, H = map(int,raw_input().split(" "))
	if W == H == 0: 
		break
	field = [[c for c in raw_input()] for _ in range(H)]
	secret = [0, ""]
	for j in range(H):
		for i in range(W):
			if not field[j][i].isdigit():
				continue
			left = top = ""
			if i > 0 and field[j][i-1].isdigit() and field[j][i-1] != "0":
				left = field[j][i-1]
			if j > 0 and field[j-1][i].isdigit() and field[j-1][i] != "0":
				top = field[j-1][i]
			if len(left) == len(top):
				field[j][i] = (left if left > top else top) + field[j][i]
			else :
				field[j][i] = (left if len(left) > len(top) else top) + field[j][i]
			length = len(field[j][i])
			if length > secret[0]:
				secret[1] = field[j][i]
				secret[0] = length
			elif length == secret[0] and field[j][i] > secret[1]:
				secret[1] = field[j][i]
	print secret[1]

Solution (Python):
while 1:
    W,H = map(int,raw_input().split())
    if W == 0: break
    C = [list(raw_input()) for _ in xrange(H)]
    
    dp = [["0"]*W for _ in xrange(H)]
    ans = 0
    for h in xrange(H):
        for w in xrange(W):
            if C[h][w].isdigit():
                dp[h][w] = str(max(int(dp[h][w]),int(C[h][w])))
                if w > 0: dp[h][w] = str(max(int(dp[h][w]),int(dp[h][w-1]+C[h][w])))
                if h > 0: dp[h][w] = str(max(int(dp[h][w]),int(dp[h-1][w]+C[h][w])))
                ans = max(ans, int(dp[h][w]))
    print ans

Solution (Python):
while 1:
    W,H = map(int,raw_input().split())
    if W == 0: break
    C = [list(raw_input()) for _ in xrange(H)]
    dp = [[0]*W for _ in xrange(H)]
    ans = 0
    for h in xrange(H):
        for w in xrange(W):
            if C[h][w].isdigit():
                dp[h][w] = max(dp[h][w],int(C[h][w]))
                if w > 0: dp[h][w] = max(dp[h][w],int(str(dp[h][w-1])+C[h][w]))
                if h > 0: dp[h][w] = max(dp[h][w],int(str(dp[h-1][w])+C[h][w]))
                ans = max(ans,dp[h][w])
    print ans

Solution (Python):
while 1:
    W,H = map(int,raw_input().split())
    if W == 0: break
    C = [list(raw_input()) for _ in xrange(H)]
    dp = [[0]*W for _ in xrange(H)]
    ans = 0
    for h in xrange(H):
        for w in xrange(W):
            if C[h][w].isdigit():
                dp[h][w] = max(dp[h][w],int(C[h][w]))
                if w > 0: dp[h][w] = max(dp[h][w],int(str(dp[h][w-1])+C[h][w]))
                if h > 0: dp[h][w] = max(dp[h][w],int(str(dp[h-1][w])+C[h][w]))
    print max(max(i) for i in dp)

Solution (Python):


import sys

while True:
    w, h = map(int, sys.stdin.readline().split( " " ) )
    if w == 0 and h == 0:
        break
    table = []
    for i in range(h):
        table.append( sys.stdin.readline() )

    dp = [[0 for i in range(w + 1)] for j in range(h + 1)]
    for i in range( h ):
        for j in range( w ):
            if '0' <= table[ i ][ j ] <= '9' :
                val = ord( table[ i ][ j ] ) - ord( '0' )
                dp[ i + 1 ][ j + 1 ] = max( dp[ i ][ j + 1 ], dp[ i + 1 ][ j ] ) * 10 + val
    print max( [ max( dp[ i ] ) for i in range( h + 1 ) ] )

Solution (Python):

def maxs(s1, s2):
    if len(s1) > len(s2): return s1
    elif len(s1) < len(s2): return s2
        
    if s1 > s2: return s1
    else: return s2

def nozero(st):
    return st.lstrip('0')

while True:
    Map=[]
    w,h=map(int,raw_input().split(' '))
    if (w==0 and h==0):break
    for i in range(h):
        Map.append(raw_input())

    res=''
    
    dp=[['' for __ in range(w)] for __ in range(h)]

    for i in range(h):
        for j in range(w):
            if(Map[i][j].isalpha()):
                continue

            if j>0:
                dp[i][j]=maxs(dp[i][j],dp[i][j-1])

            if i>0:
                dp[i][j]=maxs(dp[i][j],dp[i-1][j])
                    
            dp[i][j]+=Map[i][j]
            if ('0' in dp[i][j]):dp[i][j]=nozero(dp[i][j])
            if dp[i][j] is '0':dp[i][j]=''
            res=maxs(res,dp[i][j])


    print res

Solution (Python):
drc = [(0, 1), (1, 0)]


def dfs(r, c):
    if (r, c) in memo:
        return memo[r, c]
    ret = ''
    for dr, dc in drc:
        nr, nc = r + dr, c + dc
        if nr < H and nc < W and board[nr][nc].isdigit():
            cand = dfs(nr, nc)
            if len(cand) > len(ret) or (len(cand) == len(ret) and cand > ret):
                ret = cand
    memo[r, c] = board[r][c] + ''.join(ret)
    return board[r][c] + ret


while True:
    W, H = map(int, input().split())
    if not (W | H):
        break
    board = [input() for _ in range(H)]
    memo = dict()
    ans = ''
    for r in range(H):
        for c in range(W):
            if board[r][c].isdigit() and board[r][c] != '0':
                cand = dfs(r, c)
                if len(cand) > len(ans) or (len(cand) == len(ans) and cand > ans):
                    ans = cand
    print(ans)

Solution (Python):
import string

def fun(x):
    for c in x:
        if c not in string.digits:
            return -1
    return int(x)

while(1):
    [W,H]=map(int, raw_input().split())
    if W==0: break
    A=[]
    for i in range(H):
        A.append(raw_input())
    B=[['a' for i in range(W+1)] for j in range(H+1)]
    ans=-1
    for p in range(2, H+2):
        for q in range(2, W+2):
            [j,k]=[-p,-q]
            C= map(lambda x: A[j+1][k+1]+x, ['', B[j+1][k] , B[j][k+1] ]    )
            D=sorted(sorted(C, key = lambda x: len(x) ), key= lambda x: fun(x)) [-1]
            if fun(D)!=-1:
                B[j][k]=D
                ans=max(ans,int(B[j][k]))
    print ans

Solution (Python):
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools

sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**10
mod = 998244353

def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
def pf(s): return print(s, flush=True)


def main():
    rr = []

    while True:
        w,h = LI()
        if w == 0 and h == 0:
            break
        a = [[c for c in S()] for _ in range(h)]
        t = [[0]*w for i in range(h)]
        r = 0
        for i in range(h):
            for j in range(w):
                c = a[i][j]
                if not ('0' <= c <= '9'):
                    continue
                d = int(c) + t[i][j] * 10
                if r < d:
                    r = d
                if i < h-1 and t[i+1][j] < d:
                    t[i+1][j] = d
                if j < w-1 and t[i][j+1] < d:
                    t[i][j+1] = d
        rr.append(r)

    return '\n'.join(map(str, rr))


print(main())

Solution (Python):
import sys

def maxs(s1, s2):
    if len(s1) > len(s2): return s1
    elif len(s1) < len(s2): return s2

    if s1 > s2: return s1
    else: return s2
    

while 1:
    w,h = map(int, raw_input().split())
    if not(w or h): break
    f = []
    for i in xrange(h):
        f.append(raw_input())

    ans = ''
    t = [['' for j in xrange(w)] for i in xrange(h)]
    for i in xrange(h):
        for j in xrange(w):
            if not(ord('0') <= ord(f[i][j]) <= ord('9')):
                continue
            if j>0: t[i][j] = maxs(t[i][j], t[i][j-1])
            if i>0: t[i][j] = maxs(t[i][j], t[i-1][j])
            t[i][j] += f[i][j]
            if t[i][j] is '0': t[i][j] = ''

            ans = maxs(ans, t[i][j])

    print ans

Solution (Python):
import sys
import collections

while True:
    W, H = map(int, sys.stdin.readline().split())
    if W == 0:
        break
    area = [[-10**80 for i in xrange(H + 2)] for j in xrange(W + 2)]
    result = -1
    for i in xrange(H):
        line = sys.stdin.readline().strip()
        for j in xrange(W):
            if '0' <= line[j] <= '9':
                area[j + 1][i + 1] = int(line[j])
    for i in xrange(H):
        for j in xrange(W):
            area[j + 1][i + 1] = max(area[j + 1][i + 1], area[j + 1][i + 1] + area[j + 1][i] * 10, area[j + 1][i + 1] + area[j][i + 1] * 10)
            result = max(result, area[j + 1][i + 1])
    print result

Solution (Python):
while True:
    W,H=map(int,raw_input().split())
    if W==H==0:break
    C=[raw_input() for i in range(H)]
    table=[[""]*W for i in range(H)]
    ans=0
    for y in range(H):
        for x in range(W):
            if C[y][x].isdigit():
                a,b,c=table[y-1][x],table[y][x-1],C[y][x]
                if a==b=="":
                    table[y][x]=c
                elif a=="":
                    table[y][x]=b+c
                elif b=="":
                    table[y][x]=a+c
                elif int(a)>=int(b):
                    table[y][x]=a+c
                elif int(a)<int(b):
                    table[y][x]=b+c
                ans=ans if ans>int(table[y][x]) else int(table[y][x])
    print ans

Solution (Python):


def recursion(y, x, island, dp):
    if island[y][x].isdigit() and int(island[y][x]) in range(10):        
        if y == 0 and x == 0:
            dp[y][x] = int(island[y][x])
        elif y == 0:
            if dp[y][x-1] != -1:
                dp[y][x] = dp[y][x-1] * 10 + int(island[y][x])
            else:
                dp[y][x] = int(island[y][x])
        elif x == 0:
            if dp[y-1][x] != -1:
                dp[y][x] = dp[y-1][x] * 10 + int(island[y][x])
            else:
                dp[y][x] = int(island[y][x])
        else:
            if dp[y-1][x] == -1 and dp[y][x-1] == -1:
                dp[y][x] = int(island[y][x])
            elif dp[y-1][x] == -1:
                dp[y][x] = dp[y][x-1] * 10 + int(island[y][x])
            elif dp[y][x-1] == -1:
                dp[y][x] = dp[y-1][x] * 10 + int(island[y][x])
            else:
                dp[y][x] = max(dp[y][x-1] * 10 + int(island[y][x]), dp[y-1][x] * 10 + int(island[y][x]))
    else:
        dp[y][x] = -1
        
def solve(w, h, island, dp):
    for i in range(h):
        for j in range(w):
            recursion(i, j, island, dp)
    
    print max(map(max, dp))

def func():
    '''

    '''
    while True:
        global count
        w, h = map(int, raw_input().split())

        if w == 0 and h == 0:
            break

        island = []
        count = 0
        for i in range(h):
            row = []
            line = raw_input()
            for j in line:
                row.append(j)
            island.append(row)
        
        dp = []
        for i in range(h):
            dp_row = []
            for j in range(w):
                dp_row.append(0)
            dp.append(dp_row)
        solve(w, h, island, dp)

if __name__ == '__main__':
    func()

Solution (Python):
while True:
    w,h = map(int,input().split())
    if w == 0:
        break
    c = [input() for i in range(h)]
    dp = [[0]*w for i in range(h)]
    ans = 0
    for i in range(h):
        for j in range(w):
            d = ord(c[i][j]) - ord('0')
            if not (d>=0 and d<=9):
                continue
            dp[i][j] = d
            if i > 0:
                dp[i][j] = max(dp[i][j], dp[i-1][j]*10+d)
            if j > 0:
                dp[i][j] = max(dp[i][j], dp[i][j-1]*10+d)
            ans = max(ans, dp[i][j])
    print(ans)

Solution (Python):
def isValid(row, col, ROWS, COLS):
    return row >= 0 and row < ROWS and col >= 0 and col < COLS

def search(matrix, row, col, ROWS, COLS, memo):
    if (row, col) in memo:
        return memo[(row, col)]
    
    numStrA = ''
    numStrB = ''

    rr = row + 1
    cc = col
    if isValid(rr, cc, ROWS, COLS) and matrix[rr][cc].isdigit():
        numStrA = search(matrix, rr, cc, ROWS, COLS, memo)

    rr = row
    cc = col + 1
    if isValid(rr, cc, ROWS, COLS) and matrix[rr][cc].isdigit():
        numStrB = search(matrix, rr, cc, ROWS, COLS, memo)

    numStrA = matrix[row][col] + numStrA
    numStrB = matrix[row][col] + numStrB

    if len(numStrA) > len(numStrB):
        val = numStrA
    elif len(numStrB) > len(numStrA):
        val = numStrB
    else:
        if numStrA > numStrB:
            val = numStrA
        else:
            val = numStrB

    memo[(row, col)] = val
    return val

if __name__ == '__main__':
    while True:
        COLS, ROWS = [ int(x) for x in list(filter(lambda x: x != '', \
            input().strip().split(' '))) ]
        if ROWS == 0 and COLS == 0:
            break

        matrix = []
        for _ in range(ROWS):
            matrix.append(input().strip())
        
        maxNum = 0
        memo = {}
        for row in range(ROWS):
            for col in range(COLS):
                if matrix[row][col].isdigit() and matrix[row][col] != '0':
                    maxNum = max(maxNum, int(search(matrix, row, col, ROWS, COLS, memo)))

        print(maxNum)

Solution (Python):
from collections import defaultdict
def main(w, h):
    field = [list(input()) for i in range(h)]
    d = defaultdict(str)
    for y in range(h - 1, -1, -1):
        for x in range(w - 1, -1, -1):
            if "0" <= field[y][x] <= "9":
                d[(x, y)] = field[y][x]
    for y in range(h - 1, -1, -1):
        for x in range(w - 1, -1, -1):
            if "0" <= field[y][x] <= "9":
                if len(d[(x + 1, y)]) == len(d[(x, y + 1)]):
                    d[(x, y)] = field[y][x] + max(d[(x + 1, y)], d[(x, y + 1)])
                elif len(d[(x + 1, y)]) < len(d[(x, y + 1)]):
                    d[(x, y)] = field[y][x] + d[(x, y + 1)]
                else:
                    d[(x, y)] = field[y][x] + d[(x + 1, y)]
    ans = 0
    for v in d.values():
        if v == "":
            continue
        ans = max(ans, int(v))
    print(ans)

while 1:
    w, h = map(int, input().split())
    if h == w == 0:
        break
    main(w, h)

Solution (Python):
import sys
from collections import deque

W,H,C = None,None,None
mmax = None

def main():
    global W,H,C,mmax

    while True:
        W,H = map(int,input().split())
        if not W and not H:
            return
        C = []
        mmax = [[-1]*(W+1) for _ in range(H+1)]
        for _ in range(H):
            C.append(list(input()))
        

        num = 0

        
        
        
        
        
        

        for i in reversed(range(H)):
            for j in reversed(range(W)):
                if mmax[i][j] != -1:
                    continue
                num = max(num, bfs(i,j))
        
        print(num)


def bfs(y,x):
    global W,H,C,mmax

    if not C[y][x].isdigit():
        return 0

    l = []
    queue = deque(l)
    dd = [(0,-1), (-1,0)]
    num = 0

    queue.appendleft((C[y][x],(y,x)))
    mmax[y][x] = int(C[y][x])

    while len(queue) != 0:
        s, (uy,ux) = queue.pop()
        for dy,dx in dd:
            vy,vx = uy+dy, ux+dx
            if not (0 <= vy < H and 0 <= vx < W):
                num = max(num, mmax[uy][ux])
                continue
            if C[vy][vx].isdigit():
                n = int(C[vy][vx]+s)
                if mmax[vy][vx] < n:
                    queue.appendleft((C[vy][vx]+s, (vy,vx)))
                    mmax[vy][vx] = n
            else:
                num = max(num, mmax[uy][ux])

    return num



































def visualize(mmap):
    for row in mmap:
        print(" ".join(row))

            

if __name__ == '__main__':
    main()

Solution (Python):

from collections import defaultdict,deque
from heapq import heappush, heappop
import sys
import math
import bisect
import random
def LI(): return list(map(int, sys.stdin.readline().split()))
def I(): return int(sys.stdin.readline())
def LS():return list(map(list, sys.stdin.readline().split()))
def S(): return list(sys.stdin.readline())[:-1]
def IR(n):
    return [I() for i in range(n)]
def LIR(n):
    return [LI() for i in range(n)]
def SR(n):
    return [S() for i in range(n)]
def LSR(n):
    return [LS() for i in range(n)]

sys.setrecursionlimit(1000000)
mod = 1000000007


"""
n = int(input())
k = list("mcxi")
for i in range(n):
    d = {"m":0,"c":0,"x":0,"i":0}
    a,b  = input().split()
    a = list(a)
    b = list(b)
    a.insert(0,1)
    b.insert(0,1)
    for j in range(1,len(a)):
        if a[j] in k:
            if a[j-1] in k:
                d[a[j]] += 1
            else:
                d[a[j]] += int(a[j-1])
    for j in range(1,len(b))[::-1]:
        if b[j] in k:
            if b[j-1] in k:
                d[b[j]] += 1
            else:
                d[b[j]] += int(b[j-1])
            if d[b[j]] >= 10:
                l = b[j]
                while d[l] >= 10:
                    d[l] -= 10
                    l = k[k.index(l)-1]
                    d[l] += 1
    for j in k:
        if d[j]:
            if d[j] == 1:
                print(j,end = "")
            else:
                print(str(d[j])+j,end = "")
    print()
"""


"""
while 1:
    h, w = map(int, input().split())
    if h == w == 0:
        break
    s = [list(map(int, input().split())) for i in range(h)]

    ans = 0
    for u in range(h):
        for d in range(u+2,h):
            for l in range(w):
                for r in range(l+2,w):
                    m = float("inf")
                    for i in range(u,d+1):
                        m = min(m,s[i][l],s[i][r])
                    for i in range(l,r+1):
                        m = min(m,s[u][i],s[d][i])
                    f = 1
                    su = 0
                    for i in range(u+1,d):
                        for j in range(l+1,r):
                            su += (m-s[i][j])
                            if s[i][j] >= m:
                                f = 0
                                break
                        if not f:
                            break
                    if f:
                        ans = max(ans,su)
    print(ans)
"""


"""
while 1:
    m,n = map(int, input().split())
    if m == n == 0:
        break
    ma = 7368791
    d = [0]*(ma+1)
    z = m
    for i in range(n):
        while d[z]:
            z += 1
        j = z
        while j <= ma:
            d[j] = 1
            j += z
    for j in range(z,ma+1):
        if not d[j]:
            print(j)
            break
"""


"""
def factorize(n):
    if n < 4:
        return [1,n]
    i = 2
    l = [1]
    while i**2 <= n:
        if n%i == 0:
            l.append(i)
            if n//i != i:
                l.append(n//i)
        i += 1
    l.append(n)
    l.sort()
    return l
while 1:
    b = int(input())
    if b == 0:
        break
    f = factorize(2*b)
    for n in f[::-1]:
        a = 1-n+(2*b)//n
        if a >= 1 and a%2 == 0:
            print(a//2,n)
            break
"""


"""
import sys
dp = [100]*1000000
dp_2 = [100]*1000000
dp[0] = 0
dp_2[0] = 0
for i in range(1,181):
    s = i*(i+1)*(i+2)//6
    for j in range(s,1000000):
        if dp[j-s]+1 < dp[j]:
            dp[j] = dp[j-s]+1
    if s%2:
        for j in range(s,1000000):
            if dp_2[j-s]+1 < dp_2[j]:
                dp_2[j] = dp_2[j-s]+1
while 1:
    m = int(sys.stdin.readline())
    if m == 0:
        break
    print(dp[m],dp_2[m])
"""


"""
from collections import deque
while 1:
    n = int(input())
    if n == 0:
        break
    s = [input() for i in range(n)]
    d = [s[i].count(".") for i in range(n)]
    m = max(d)
    c = [s[i][-1] for i in range(n)]
    q = deque()
    for i in range(1,m+1)[::-1]:
        j = 0
        while j < n:
            for k in range(j,n):
                if d[k] == i:break
            else:
                break
            j = k
            op = c[j-1]
            while j < n and d[j] == i:
                q.append(j)
                j += 1
            j = k
            if op == "+":
                k = 0
                while q:
                    x = q.pop()
                    k += int(c[x])
                    c.pop(x)
                    d.pop(x)
                    n -= 1
            else:
                k = 1
                while q:
                    x = q.pop()
                    k *= int(c[x])
                    c.pop(x)
                    d.pop(x)
                    n -= 1
            c[j-1] = k
    print(c[0])
"""


"""
from collections import defaultdict

def parse_expr(s,i):
    i += 1
    if s[i] == "[":
        q = []
        while s[i] != "]":
            e,i = parse_expr(s,i)
            q.append(e)
        return (calc(q),i+1)
    else:
        n,i = parse_num(s,i)
        return (calc([n]),i+1)

def parse_num(s,i):
    m = int(s[i])
    i += 1
    while f_num[s[i]]:
        m *= 10
        m += int(s[i])
        i += 1
    return (m,i)

def calc(q):
    if len(q) == 1:
        return (q[0]+1)//2
    q.sort()
    return sum(q[:len(q)//2+1])

f_num = defaultdict(lambda : 0)
for i in range(10):
    f_num[str(i)] = 1

n = int(input())
for i in range(n):
    s = input()
    print(parse_expr(s,0)[0])
"""


while 1:
    w,h = LI()
    if w == h == 0:
        break
    s = SR(h)
    dp = [[0]*w for i in range(h)]
    for y in range(h):
        for x in range(w):
            if s[y][x].isdecimal():
                dp[y][x] = max(dp[y-1][x],dp[y][x-1])*10+int(s[y][x])
    ans = 0
    for i in dp:
        ans = max(ans,max(i))
    print(ans)

Solution (Python):


import sys
sys.setrecursionlimit(10**9)
input = sys.stdin.readline


def isdigit(x):
    return '0' <= x <= '9'


def solve():
    W, H = map(int, input().split())
    if W == 0:
        exit()
    grid = [[v for v in input()[:-1]] for _ in range(H)]
    dp = [[-1]*W for _ in range(H)]

    max_val = 0
    for row in range(H):
        for col in range(W):
            if isdigit(grid[row][col]):
                if row > 0 and col > 0:
                    cand = max(dp[row-1][col], dp[row][col-1], 0)
                elif row == 0 and col == 0:
                    cand = 0
                elif row == 0:
                    cand = max(dp[row][col-1], 0)
                elif col == 0:
                    cand = max(dp[row-1][col], 0)

                dp[row][col] = cand*10+int(grid[row][col])

                max_val = max(max_val, dp[row][col])

    print(max_val)


while True:
    solve()

Solution (Python):

def check(a,b):
    if (a,b) in memo:
        return memo[(a,b)]
    if 0<=a<h and 0<=b<w and field[a][b].isdigit():
        x=check(a+1,b)
        y=check(a,b+1)
        memo[(a,b)]=field[a][b]+(x if len(x)>len(y) else x if len(x)==len(y) and len(x)!=0 and int(x)>int(y) else y)
        return field[a][b]+(x if len(x)>len(y) else x if len(x)==len(y) and len(x)!=0 and int(x)>int(y) else y)
    else:
        return ''
while 1:
    w,h=map(int,input().split())
    if w==0:
        break
    field=[]
    for i in range(h):
        field.append(list(input()))
    ans='0'
    memo={}
    for i in range(h):
        for j in range(w):
            if field[i][j]!='0' and field[i][j].isdigit():
                tmp=check(i,j)
                if int(ans)<int(tmp):
                    ans=tmp
    print(ans)