using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.Text; using System.Text.RegularExpressions; using System.Linq; class Magatro { static int W, H; static string[] C; static int[] Xp = new int[] { 1, -1, 0, 0 }; static int[] Yp = new int[] { 0, 0, 1, -1 }; static void Main() { Read(); List L1 = new List(); bool[,] Looked = new bool[H, W]; bool q = false; for (int i = 0; i < H; i++) { for (int j = 0; j < W; j++) { if (C[i][j] == '.') { Stack ST = new Stack(); ST.Push(new XY(i, j)); Looked[i, j] = true; while (ST.Count > 0) { XY Po = ST.Peek(); bool a = true; for(int k = 0; k < 4; k++) { XY N = new XY(Po.Y+Yp[k],Po.X+Xp[k]); if (C[N.Y][N.X] == '.') { if (!Looked[N.Y, N.X]) { // Console.WriteLine("a"); Looked[N.Y, N.X] = true; a = false; ST.Push(N); break; } } } if (a) { L1.Add(ST.Pop()); } } q = true; break; } } if (q) { break; } } q = false; List L2 = new List(); for (int i = 0; i < H; i++) { for (int j = 0; j < W; j++) { if (C[i][j] == '.'&&!Looked[i,j]) { Stack ST = new Stack(); ST.Push(new XY(i, j)); Looked[i, j] = true; while (ST.Count > 0) { XY Po = ST.Peek(); bool a = true; for (int k = 0; k < 4; k++) { XY N = new XY(Po.Y + Yp[k], Po.X + Xp[k]); if (C[N.Y][N.X] == '.') { if (!Looked[N.Y, N.X]) { // Console.WriteLine("{0} {1}", N.Y, N.X); Looked[N.Y, N.X] = true; a = false; ST.Push(N); break; } } } if (a) { L2.Add(ST.Pop()); } } q = true; break; } } if (q) { break; } } int min = int.MaxValue; for(int i = 0; i < L1.Count; i++) { for(int j = 0; j < L2.Count; j++) { min = Math.Min(min, Dist(L1[i], L2[j])); } } Console.WriteLine(min); } static int Dist(XY a,XY b) { return Math.Abs(a.X - b.X) + Math.Abs(a.Y - b.Y)-1; } static void Read() { string[] s = Console.ReadLine().Split(' '); W = int.Parse(s[0]); H = int.Parse(s[1]); C = new string[H]; for(int i = 0; i < H; i++) { C[i] = Console.ReadLine(); } } } struct XY { public int Y, X; public XY(int y,int x) { Y = y; X = x; } public static XY operator +(XY a,XY b) { return new XY(a.Y + b.Y, a.X + b.X); } }