n,m = map(int,input().split()) a = [list(map(int,input().split())) for i in range(n)] if n == 1: print(0); exit() from heapq import heappop, heappush INF = 10**15 dist = [[INF]*(m) for i in range(n)]*(n+1) que = [] for i in range(m): heappush(que, (a[n-1][i],n-1, i)) dist[n-1][i] = a[n-1][i] while que: c, x,y = heappop(que) if c > dist[x][y]: continue for nxt in range(m): anxt = a[x][nxt] if dist[x][y] + anxt < dist[x][nxt]: dist[x][nxt] = dist[x][y] + anxt heappush(que,(dist[x][nxt],x,nxt)) if x != 0: if dist[x][y] + a[x-1][y] < dist[x-1][y]: dist[x-1][y] = dist[x][y] + a[x-1][y] heappush(que, (dist[x-1][y], x-1, y)) print(min(dist[0]))