import scala.collection.immutable.Queue

object Main {

  def main(args: Array[String]): Unit = {
    val sc = new java.util.Scanner(System.in)

    val H, W = sc.nextInt(); sc.nextLine()
    val S = Array.fill(H)(sc.nextLine().trim.toCharArray)
    // スタートの決定にO(H*W)
    // ゴールの決定にO(H*W)
    // 最短路の探索にO(H*W)
    // 全探索するとO(H^3*W^3)
    // 64 * 10^6で間に合わない
    // dist(y)(x)(y')(x') := マスy,xからマスy',x'への最短路としておく
    def solve(H: Int, W: Int, S: Array[Array[Char]]): Int = {
      val MAX = Int.MaxValue
      val dist = Array.fill(H, W, H, W)(MAX)
      val dx = Array(0, 0, -1, 1)
      val dy = Array(-1, 1, 0, 0)

      def bfs(sx: Int, sy: Int, ex: Int, ey: Int): Int = {
        val UNREACHED = 401
        val arr = Array.fill(H, W)(MAX)
        arr(sy)(sx) = 0
        def loop(queue: Queue[(Int, Int)], min: Int): Int = {
          if (queue.nonEmpty) {
            val (x, y) = queue.head
            dist(sy)(sx)(y)(x) = dist(sy)(sx)(y)(x) min arr(y)(x)
            dist(y)(x)(sy)(sx) = dist(y)(x)(sy)(sx) min arr(y)(x)
            if (x == ex && y == ey) {
              loop(queue.tail, min min arr(ey)(ex))
            } else if (dist(y)(x)(ey)(ex) != MAX) {
              loop(queue.tail, min min (arr(y)(x) + dist(y)(x)(ey)(ex)))
            } else {
              loop((0 until 4).foldLeft(queue.tail) { (queue, i) =>
                val nx = x + dx(i)
                val ny = y + dy(i)
                if (nx >= 0 && nx < W &&
                  ny >= 0 && ny < H &&
                  S(ny)(nx) == '.' &&
                  arr(ny)(nx) == MAX) {
                  arr(ny)(nx) = arr(y)(x) + 1
                  queue.enqueue((nx, ny))
                } else queue
              }, min)
            }
          } else min
        }
        val r = loop(Queue((sx, sy)), UNREACHED)
        if (r == UNREACHED) 0
        else r
      }

      (for {
        sy <- 0 until H
        sx <- 0 until W
        if (S(sy)(sx) == '.')
        ey <- 0 until H
        ex <- 0 until W
        if (S(ey)(ex) == '.')
      } yield bfs(sx, sy, ex, ey)).max
    }

    println(solve(H, W, S))
  }

}
