#include <bits/stdc++.h>
using namespace std;
int a[100][100];
int main() {
  int n, m, ans = 100;
  cin >> n >> m;
  for (int i = 1; i <= n; i++)
    for (int j = 1; j <= m; j++) {
      cin >> a[i][j];
      if (a[i][j]) {
        int ad = 0;
        if (i == 1 || i == n || j == 1 || j == m)
          ad = 2;
        else
          ad = 4;
        ans = min(ad, ans);
      }
    }
  cout << ans << endl;
  return 0;
}
