def solve1(H, W, S): L = [(0,0)] Seen = [[False] * W for _ in range(H)] add_one_possible = False add_zero_possible = False dx = [1, 0] dy = [0, 1] while len(L): (x, y) = L.pop() if(x == H - 1 and y == W - 1): add_zero_possible = True break if(x >= H - 2 or y >= W - 2): add_one_possible = True for k in range(2): x2 = x + dx[k] y2 = y + dy[k] if(x2 < H and y2 < W and S[x2][y2] != "#" and not Seen[x2][y2]): Seen[x2][y2] = True L.append((x2, y2)) if(add_zero_possible): return (H + W - 2) elif(add_one_possible): return (H + W - 1) else: return (H + W) def solve2(H, W, S): L = [(0,0)] Seen = [[False] * W for _ in range(H)] dx = [1, 0] dy = [0, 1] S_height = 0 S_width = 0 while len(L): (x, y) = L.pop() if(x == H - 1 and y == W - 1): return (H + W - 2) S_height = max(x, S_height) S_width = max(y, S_width) for k in range(2): x2 = x + dx[k] y2 = y + dy[k] if(x2 < H and y2 < W and S[x2][y2] != "#" and not Seen[x2][y2]): Seen[x2][y2] = True L.append((x2, y2)) L = [(H - 1,W - 1)] Seen = [[False] * W for _ in range(H)] dx = [-1, 0] dy = [0, -1] G_height = H - 1 G_width = W - 1 while len(L): (x, y) = L.pop() G_height = min(x, G_height) G_width = min(y, G_width) for k in range(2): x2 = x + dx[k] y2 = y + dy[k] if(0 <= x2 and 0 <= y2 and S[x2][y2] != "#" and not Seen[x2][y2]): Seen[x2][y2] = True L.append((x2, y2)) # print(S_height, S_width, G_height, G_width) if(G_height - S_height <= 1 or G_width - S_width <= 1): return (H + W -1) else: return (H + W) H, W = map(int, input().split()) S = [input() for _ in range(H)] print(solve2(H, W, S)) # import random # random.seed(41) # while True: # H = random.randint(2, 3) # W = random.randint(2, 3) # S = [["." for _ in range(W)] for _ in range(H)] # S[0][0] = "S" # S[H - 1][W - 1] = "G" # for i in range(H): # for j in range(W): # if(S[i][j] != "."): # continue # if(random.random() < 0.6): # S[i][j] = "#" # ans1 = solve1(H, W, S) # ans2 = solve2(H, W, S) # if(ans1 != ans2): # print(H, W) # for i in range(H): # print("".join(S[i])) # print(ans1, ans2) # break