#include <bits/stdc++.h>
using namespace std;
int main() {
  int n, m;
  cin >> n >> m;
  char input[n][m];
  vector<int> result;
  for (long long i = 0; i < n; i++)
    for (long long j = 0; j < m; j++) {
      cin >> input[i][j];
    }
  for (long long i = 0; i < n; i++) {
    for (long long j = 0; j < m; j++) {
      if ((i == 0 || i == n - 1) && (j == 0 || j == m - 1) &&
          input[i][j] == '1') {
        result.push_back(1);
      } else if ((i == 0 || i == n - 1 || j == 0 || j == m - 1) &&
                 input[i][j] == '1') {
        result.push_back(2);
      } else if (input[i][j] == '1') {
        result.push_back(4);
      }
    }
  }
  cout << *min_element(result.begin(), result.end()) << endl;
  return 0;
}
