#include <bits/stdc++.h>
using namespace std;
const int MAXN = (int)(1e3) + 100;
const int INF = (int)(1e9);
const double EPS = 1e-8;
int n, m, d[MAXN][MAXN], cnt;
int main() {
  cin >> n >> m;
  for (int i = 1; i <= n; i++)
    for (int j = 1; j <= m; j++) cin >> d[i][j];
  for (int i = 1; i <= n; i++) {
    if (d[i][1] == 1 || d[i][m] == 1) {
      cout << 2 << endl;
      return 0;
    }
  }
  for (int i = 1; i <= m; i++) {
    if (d[n][i] == 1 || d[1][i] == 1) {
      cout << 2 << endl;
      return 0;
    }
  }
  cout << 4 << endl;
  return 0;
}
