#include <bits/stdc++.h>
using namespace std;
#define gc getchar_unlocked
#define fo(i,n) for(i=0;i<n;i++)
#define Fo(i,k,n) for(i=k;k<n?i<n:i>n;k<n?i+=1:i-=1)
#define ll long long
#define si(x) scanf("%d",&x)
#define sl(x) scanf("%lld",&x)
#define ss(s) scanf("%s",s)
#define pi(x) prllf("%d\n",x)
#define pl(x) prllf("%lld\n",x)
#define ps(s) prllf("%s\n",s)
#define pb push_back
#define mp make_pair
#define F first
#define S second
#define all(x) x.begin(), x.end()
#define clr(x) memset(x, 0, sizeof(x))
#define sortall(x) sort(all(x))
#define tr(it, a) for(auto it = a.begin(); it != a.end(); it++)
#define PI 3.1415926535897932384626
typedef pair<ll, ll> pii;
typedef pair<ll, ll> pll;
typedef vector<ll> vi;
typedef vector<ll> vll;
typedef vector<pii> vpii;
typedef vector<pll> vpll;
typedef vector<vi> vvi;
typedef vector<vll> vvl;
const ll mod = 1000000007;
const ll N = 1003;
vi g[N];
ll a[N][N], dp[N][N];
ll dx[] = {+1, +1, +1, -1, -1, -1, +0, +0};
ll dy[] = {-1, +1, +0, -1, +1, +0, +1, -1};
ll n, m;
ll vis[N][N], x1, Y1, x2, y2, T;
bool val(ll x, ll y){
return x<=n and y<=m and x>=1 and y>=1;
}
void fill(ll x, ll y){
vis[x][y] = 1;
ll i;
fo(i, 8){
ll nx = x+dx[i];
ll ny = y+dy[i];
if(!val(nx, ny) or vis[nx][ny] or a[nx][ny] != 1) continue;
fill(nx, ny);
}
}
void go(ll x, ll y){
vis[x][y] = 1;
T++;
x1 = min(x1, x);
x2 = max(x2, x);
Y1 = min(Y1, y);
y2 = max(y2, y);
ll i;
fo(i, 8){
ll nx = x+dx[i];
ll ny = y+dy[i];
if(!val(nx, ny) or vis[nx][ny] or a[nx][ny] != 1) continue;
go(nx, ny);
}
}
ll sum(ll x1, ll Y1, ll x2, ll y2){
return dp[x2][y2] + dp[x1-1][Y1-1] - dp[x1-1][y2] - dp[x2][Y1-1];
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
ll i,k,j;
cin>>n>>m;
fo(i, n) fo(j, m)cin>>a[i+1][j+1];
fo(i, n+1) dp[i][0] = 0;
fo(i, m+1) dp[0][i] = 0;
Fo(i, 1, n+1)
Fo(j, 1, m+1) dp[i][j] = a[i][j] + dp[i-1][j] + dp[i][j-1] - dp[i-1][j-1];
// cout<<sum(2,2,2,3)<<endl;
Fo(i, 1, n+1)
if(a[i][1] and !vis[i][1]) fill(i, 1);
Fo(i, 1, n+1)
if(a[i][m] and !vis[i][m]) fill(i, m);
Fo(i, 1, m+1)
if(a[1][i] and !vis[1][i]) fill(1, i);
Fo(i, 1, m+1)
if(a[n][i] and !vis[n][i]) fill(n, i);
ll ans = 0;
Fo(i, 2, n)
Fo(j, 2, m){
if(vis[i][j] or a[i][j]==0) continue;
x1 = Y1 = mod;
x2 = y2 = 0;
T = 0;
go(i, j);
// cout<<T<<" "<<x1<<" "<<Y1<<" "<<x2<<" "<<y2<<endl;
if(sum(x1, Y1, x2, y2) == (x2-x1+1)*(y2-Y1+1)) ans = max(ans, T);
}
ans = ans==0?-1:ans;
cout<<ans<<endl;
return 0;
}
I2luY2x1ZGUgPGJpdHMvc3RkYysrLmg+CnVzaW5nIG5hbWVzcGFjZSBzdGQ7CiNkZWZpbmUgZ2MgZ2V0Y2hhcl91bmxvY2tlZAojZGVmaW5lIGZvKGksbikgZm9yKGk9MDtpPG47aSsrKQojZGVmaW5lIEZvKGksayxuKSBmb3IoaT1rO2s8bj9pPG46aT5uO2s8bj9pKz0xOmktPTEpCiNkZWZpbmUgbGwgbG9uZyBsb25nCiNkZWZpbmUgc2koeCkJc2NhbmYoIiVkIiwmeCkKI2RlZmluZSBzbCh4KQlzY2FuZigiJWxsZCIsJngpCiNkZWZpbmUgc3MocykJc2NhbmYoIiVzIixzKQojZGVmaW5lIHBpKHgpCXBybGxmKCIlZFxuIix4KQojZGVmaW5lIHBsKHgpCXBybGxmKCIlbGxkXG4iLHgpCiNkZWZp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