import Queue W, H = map(int, raw_input().split()) C = [raw_input() for _ in xrange(H)] color = [[0 for _ in xrange(W)] for _ in xrange(H)] currentColor = 1 for i in xrange(H): for j in xrange(W): if C[i][j] != '#' and color[i][j] == 0: q = Queue.Queue() q.put((i, j)) color[i][j] = currentColor while not q.empty(): y, x = q.get() for dy, dx in [(0, 1), (1, 0), (0, -1), (-1, 0)]: ny = y + dy nx = x + dx if ny < 0 or ny >= H or nx < 0 or nx >= W: continue if C[ny][nx] == '#': continue if color[ny][nx] != 0: continue color[ny][nx] = currentColor q.put((ny, nx)) currentColor += 1 sy, sx, gy, gx = 0, 0, 0, 0 for i in xrange(H): for j in xrange(W): if color[i][j] == 1: sy, sx = i, j elif color[i][j] == 2: gy, gx = i, j inf = 10 ** 10 dist = [[inf for _ in xrange(W)] for _ in xrange(H)] dist[sy][sx] = 0 q = Queue.PriorityQueue() q.put((0, sy, sx)) while not q.empty(): _, y, x = q.get() for dy, dx in [(1, 0), (0, 1), (-1, 0), (0, -1)]: ny = y + dy nx = x + dx if ny < 0 or ny >= H or nx < 0 or nx >= W: continue if color[ny][nx] == 0: cost = 1 else: cost = 0 if dist[ny][nx] > dist[y][x] + cost: dist[ny][nx] = dist[y][x] + cost q.put((dist[ny][nx], ny, nx)) print dist[gy][gx]