import strutils, sequtils, algorithm, math var wh = split(readLine(stdin), ' ').map(parseInt) count = 0 board = newSeq[seq[int]](wh[1]) dire = [[0, -1], [1, 0], [0, 1], [-1, 0]] pre = 0 proc bfs(x, y, count: int): int = var min_dis = high(int) if count == 0: for i in countup(1, wh[1] - 2): for j in countup(1, wh[0] - 2): if board[i][j] == 1: for d in dire: if 0 < j + d[0] and j + d[0] < wh[0] - 1 and 0 < i + d[1] and i + d[1] < wh[1] - 1: if board[i+d[1]][j+d[0]] == -1: min_dis = min(bfs(j + d[0], i + d[1], count + 1), min_dis) return min_dis else: board[y][x] = -2 for d in dire: if 0 < x + d[0] and x + d[0] < wh[0] - 1 and 0 < y + d[1] and y + d[1] < wh[1] - 1: if board[y+d[1]][x+d[0]] == 2: board[y][x] = -1 return count for d in dire: if 0 < x + d[0] and x + d[0] < wh[0] - 1 and 0 < y + d[1] and y + d[1] < wh[1] - 1: if board[y+d[1]][x+d[0]] == -1: min_dis = min(bfs(x + d[0], y + d[1], count + 1), min_dis) board[y][x] = -1 return min_dis proc init(pre: var int; x, y: int) = if pre == 0: for i in countup(1, wh[1] - 2): for j in countup(1, wh[0] - 2): if board[i][j] == 0: pre += 1 board[i][j] = pre for d in dire: init(pre, j + d[0], i + d[1]) else: if board[y][x] == 0: board[y][x] = pre for d in dire: if 0 < x + d[0] and x + d[0] < wh[0] - 1 and 0 < y + d[1] and y + d[1] < wh[1] - 1: init(pre, x + d[0], y + d[1]) for i in countup(0, wh[1] - 1): var line = readLine(stdin) var row = newSeq[char](0) for c in line: row.add(c) board[i] = row.map(proc (x: char): int = result = if x == '#': -1 else: 0 return) init(pre, 1, 1) echo(bfs(0, 0, 0))