#include <bits/stdc++.h>
using namespace std;
int dx[] = {1, 0, -1, 0};
int dy[] = {0, 1, 0, -1};
int main() {
  int n, m, x, c = 0;
  bool f = 0, b = 0;
  cin >> n >> m;
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < m; j++) {
      cin >> x;
      if (x == 1) {
        c++;
        if ((i == 0 && j == 0) || (i == 0 && j == m - 1) ||
            (i == n - 1 && j == 0) || (i == n - 1 && j == m - 1))
          f = 1;
        else if (i == 0 || j == 0 || i == n - 1 || j == m - 1)
          b = 1;
      }
    }
  }
  if (f)
    cout << "1\n";
  else if (b)
    cout << "2\n";
  else
    cout << "4\n";
}
