#include <bits/stdc++.h>
const long long INF = 200000000000000;
const double PI = 3.14159265358979323846;
const long long MOD = 1000000000 + 7;
using namespace std;
int main() {
  int n, m, k(0), ans = 4;
  bool a[50][50];
  cin >> n >> m;
  for (int i(0); i < n; i++) {
    for (int j(0); j < m; j++) {
      cin >> a[i][j];
      if (a[i][j] == 1 && (i == 0 || j == 0 || i == n - 1 || j == m - 1)) {
        ans = 2;
        break;
      }
    }
  }
  cout << ans;
}
