from collections import deque H, W = map(int, input().split()) S = [input() for _ in range(H)] visited = [[-1]*W for _ in range(H)] visited[0][0] = (0, 0) que = deque() que.append((0, 0)) direction = [(-1,0),(0,1),(1,0),(0,-1)] while que: h, w = que.popleft() wcnt, hcnt = visited[h][w] for dh, dw in direction: nh, nw = h+dh, w+dw if 0<=nh