import java.util.Scanner import scala.collection.mutable object Problem157 { type Point = (Int, Int) def splitField(field: Array[Array[String]]): (Seq[(Point)], Seq[(Point)]) = { val allSpaces: Seq[(Point)] = { for { (row, i) <- field.zipWithIndex (col, j) <- row.zipWithIndex if col == "." } yield { (i, j) } }.toSeq val checked = mutable.Set[(Point)]() val queue = mutable.Queue[(Point)]() checked += allSpaces.head queue += allSpaces.head while (queue.nonEmpty) { val space = queue.dequeue() for { dir <- Seq((-1, 0), (1, 0), (0, -1), (0, 1)) row = space._1 + dir._1 col = space._2 + dir._2 if field(row)(col) == "." if !checked.contains(row, col) } { checked += ((row, col)) queue += ((row, col)) } } val room1 = checked.toSeq val room2 = allSpaces diff room1 (room1, room2) } def proc(w: Int, h: Int, field: Array[Array[String]]): Int = { val (room1, room2) = splitField(field) val dists = for { a <- room1 b <- room2 } yield { (a._1 - b._1).abs + (a._2 - b._2).abs - 1 } dists.min } def main(args: Array[String]) { val sc = new Scanner(System.in) val w = sc.nextInt() val h = sc.nextInt() val field = Array.fill(h)(sc.next().split("")) val result: Int = proc(w, h, field) println(result) } }