#include <bits/stdc++.h>
using namespace std;
int table[100][100];
bool canOne(int n, int m) {
  if (table[1][1] == 1 || table[1][m] == 1 || table[n][1] == 1 ||
      table[n][m] == 1)
    return true;
  else
    return false;
}
bool canTwo(int n, int m) {
  int i, j;
  for (i = 1; i <= n; i++) {
    if (table[i][1] == 1) return true;
    if (table[i][m] == 1) return true;
  }
  for (i = 1; i <= m; i++) {
    if (table[1][i] == 1) return true;
    if (table[n][i] == 1) return true;
  }
  return false;
}
int main() {
  int i, j, n, m;
  while (scanf("%d%d", &n, &m) != EOF) {
    for (i = 1; i <= n; i++)
      for (j = 1; j <= m; j++) scanf("%d", &table[i][j]);
    if (canOne(n, m))
      printf("%d\n", 1);
    else if (canTwo(n, m))
      printf("%d\n", 2);
    else
      printf("%d\n", 4);
  }
  return 0;
}
