import math._ import scala.util.control.Breaks._ import scala.collection.mutable.Queue object Main { def display(tab: Array[Array[Boolean]]) { for (xs <- tab) { for (j <- 0 to xs.length-1) { if (xs(j)) print("o") else print("x") } println() } } def calc(rows: Int, cols: Int, g: Array[Array[Char]]): Int = { var tab = Array.fill(rows, cols)(false) val pos = (for (i <- 0 to rows-1; j <- 0 to cols-1 if g(i)(j) == '.') yield (i, j)).head var q = new Queue[(Int, Int)] q.enqueue((pos._1, pos._2)) while (!q.isEmpty) { val (r, c) = q.dequeue if (g(r)(c) == '.' && !tab(r)(c)) { tab(r)(c) = true for ((dr, dc) <- Array((-1, 0), (1, 0), (0, -1), (0, 1))) { val row = r + dr val col = c + dc if (0 <= row && row < rows && 0 <= col && col < cols) { if (g(row)(col) == '.') { q.enqueue((row, col)) } } } } } var ans = Integer.MAX_VALUE for (i <- 0 to rows-1; j <- 0 to cols-1) { if (tab(i)(j)) { for (k <- 0 to rows-1; m <- 0 to cols-1) { if (g(k)(m) == '.' && !tab(k)(m)) { ans = min(ans, abs(i - k) + abs(j - m) - 1) } } } } ans } def main(args: Array[String]) { val sc = new java.util.Scanner(System.in) val W, H = sc.nextInt val g = Array.fill(H, W)(' ') for (i <- 0 to H-1) { val s = sc.next for (j <- 0 to W-1) { g(i)(j) = s(j) } } println(calc(H, W, g)) } }