#include <bits/stdc++.h>
using namespace std;
const long long Mod = 7 + 1e9;
const long long INF32 = 5 + 2e9;
const long long INF64 = 1 + 1e18;
const long long MAX = 5 + 3e5;
int N, M, ans = 4;
int main() {
  cin >> N >> M;
  for (int i = 1; i <= N; i++)
    for (int j = 1; j <= M; j++) {
      bool b;
      cin >> b;
      if (b && (i == 1 || j == 1 || i == N || j == M)) {
        ans = 2;
        break;
      }
    }
  cout << ans << endl;
  return 0;
}
