#include <bits/stdc++.h>
int main() {
  int n, m, count = 0, i, j, flag = 4;
  scanf("%d %d", &n, &m);
  int a[n + 5][m + 5];
  for (i = 1; i <= n; i++) {
    for (j = 1; j <= m; j++) {
      scanf("%d", &a[i][j]);
      if (a[i][j] != 0) {
        count++;
        if (i == 1 || i == n || j == 1 || j == m) flag = 2;
      }
    }
  }
  if (count == (n * m))
    printf("0\n");
  else
    printf("%d\n", flag);
  return 0;
}
