Problem:
Score : 400 points

Problem Statement

Takahashi has a maze, which is a grid of H \times W squares with H horizontal rows and W vertical columns.

The square at the i-th row from the top and the j-th column is a "wall" square if S_{ij} is #, and a "road" square if S_{ij} is ..

From a road square, you can move to a horizontally or vertically adjacent road square.

You cannot move out of the maze, move to a wall square, or move diagonally.

Takahashi will choose a starting square and a goal square, which can be any road squares, and give the maze to Aoki.

Aoki will then travel from the starting square to the goal square, in the minimum number of moves required.

In this situation, find the maximum possible number of moves Aoki has to make.

Constraints

1 \leq H,W \leq 20

S_{ij} is . or #.

S contains at least two occurrences of ..

Any road square can be reached from any road square in zero or more moves.

Input

Input is given from Standard Input in the following format:

H W
S_{11}...S_{1W}
:
S_{H1}...S_{HW}

Output

Print the maximum possible number of moves Aoki has to make.

Sample Input 1

3 3
...
...
...

Sample Output 1

4

If Takahashi chooses the top-left square as the starting square and the bottom-right square as the goal square, Aoki has to make four moves.

Sample Input 2

3 5
...#.
.#.#.
.#...

Sample Output 2

10

If Takahashi chooses the bottom-left square as the starting square and the top-right square as the goal square, Aoki has to make ten moves.

Solution in Ruby (2.3.3) (judge verdict: Accepted)

# frozen_string_literal: true
require 'thread'

@h, @w, @k = gets.split.map(&:to_i)
@s = @h.times.map { gets.chomp }

def left(x, y)
  if y.zero? || @s[x][y - 1] != '.'
    [x, y]
  else
    [x, y - 1]
  end
end

def right(x, y)
  if y == @w - 1 || @s[x][y + 1] != '.'
    [x, y]
  else
    [x, y + 1]
  end
end

def up(x, y)
  if x.zero? || @s[x - 1][y] != '.'
    [x, y]
  else
    [x - 1, y]
  end
end

def down(x, y)
  if x == @h - 1 || @s[x + 1][y] != '.'
    [x, y]
  else
    [x + 1, y]
  end
end

def nextp(x, y)
  if y == @w - 1
    if x == @h - 1
      nil
    else
      [x + 1, 0]
    end
  else
    [x, y + 1]
  end
end

starts = []
goals = []
0.upto(@h - 1) do |i|
  0.upto(@w - 1) do |j|
    if @s[i][j] == '.'
      starts.push [i, j]
      goals.push [i, j]
    end
  end
end
max = 0

def maze(start, goal)
  return 0 if @s[start[0]][start[1]] == '#'

  q = Queue.new
  c = Array.new(@h) { Array.new(@w) { -1 } }
  c[start[0]][start[1]] = 0

  max = 0
  q.push start
  loop do
    break if q.empty?

    p = q.pop
    x = p[0]
    y = p[1]
    count = c[x][y]
    max = count if max < count

    [left(x, y), right(x, y), up(x, y), down(x, y)].each do |np|
      xx = np[0]
      yy = np[1]
      if c[xx][yy].negative?
        q.push [xx, yy]
        c[xx][yy] = count + 1
      end
    end
  end
  max
end

starts.each do |start|
  d = maze(start, start)
  max = d if max < d
end

puts max