#include <bits/stdc++.h>
using namespace std;
int main() {
  int n, m, i, j, x1;
  int xy[50][50];
  cin >> n >> m;
  for (i = 0; i < n; i++) {
    for (j = 0; j < m; j++) {
      cin >> xy[i][j];
    }
  }
  x1 = 4;
  for (i = 0; i < n; i++) {
    if ((xy[i][0] == 1) || (xy[i][m - 1] == 1)) {
      x1 = 2;
      break;
    }
  }
  for (j = 0; j < m; j++) {
    if ((xy[0][j] == 1) || (xy[n - 1][j] == 1)) {
      x1 = 2;
      break;
    }
  }
  cout << x1 << endl;
  return 0;
}
