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