#include <bits/stdc++.h>
using namespace std;
int grid[50][50];
int main() {
  int height, width;
  cin >> height >> width;
  for (int i = 0; i < height; i++) {
    for (int j = 0; j < width; j++) cin >> grid[i][j];
  }
  if (grid[0][0] || grid[height - 1][0] || grid[0][width - 1] ||
      grid[height - 1][width - 1]) {
    cout << 1 << endl;
    return 0;
  }
  for (int i = 0; i < height; i++) {
    if (grid[i][0] || grid[i][width - 1]) {
      cout << 2 << endl;
      return 0;
    }
  }
  for (int i = 0; i < width; i++) {
    if (grid[0][i] || grid[height - 1][i]) {
      cout << 2 << endl;
      return 0;
    }
  }
  cout << 4 << endl;
  return 0;
}
