https://www.acmicpc.net/problem/17086
using System;
using System.Collections;
class Program
{
static int[,] arr;
static bool[,] check;
static int n,m;
static int[] dx= {0,0,1,-1,1,1,-1,-1};
static int[] dy= {1,-1,0,0,1,-1,-1,1};
static int bfs(int a,int b){
check=new bool[n+1,m+1];
Queue q=new Queue();
q.Enqueue(new int[]{a,b,0});
check[a,b]=true;
while(q.Count!=0){
int[] v=(int[])q.Dequeue();
for(int i=0;i<8;i++){
int x=v[0]+dx[i];
int y=v[1]+dy[i];
int z=v[2]+1;
if(x<0 || x>=n || y<0 || y>=m || check[x,y]==true) continue;
if(arr[x,y]==1) return z;
q.Enqueue(new int[]{x,y,z});
check[x,y]=true;
}
}
return 0;
}
static void Main() {
string[] s=Console.ReadLine().Split(' ');
n=int.Parse(s[0]);
m=int.Parse(s[1]);
arr=new int[n+1,m+1];
for(int i=0;i<n;i++){
string[] s1=Console.ReadLine().Split(' ');
for(int j=0;j<m;j++){
arr[i,j]=int.Parse(s1[j]);
}
}
int count=0;
int num=0;
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
if(arr[i,j]!=1){
num=bfs(i,j);
count=num>count?num:count;
}
}
}
Console.Write(count);
}
}