#include <iostream>
int i, j, k, A[1002][1002], B[1002][1002], N, M;
int F(int x, int y) {
if (x == 0 || y == 0 || x == N+1 || y == M+1 || B[x][y] == 1) return 0;
B[x][y] = 1;
--k;
if (A[x-1][y] == 4) F(x-1, y);
if (A[x+1][y] == 2) F(x+1, y);
if (A[x][y-1] == 1) F(x, y-1);
if (A[x][y+1] == 3) F(x, y+1);
return 0;
}
int main() {
std::cin >> N >> M;
k = N*M;
for (i=1; i<=N; ++i)
for (j=1; j<=M; ++j)
std::cin >> A[i][j];
if (A[1][1] == 2 || A[1][1] == 3) F(1, 1);
if (A[1][M] == 1 || A[1][M] == 2) F(1, M);
if (A[N][M] == 1 || A[N][M] == 4) F(N, M);
if (A[N][1] == 3 || A[N][1] == 4) F(N, 1);
for (i=2; i<M; ++i)
if (A[1][i] == 2) F(1, i);
for (i=2; i<M; ++i)
if (A[N][i] == 4) F(N, i);
for (i=2; i<N; ++i)
if (A[i][1] == 3) F(i, 1);
for (i=2; i<N; ++i)
if (A[i][M] == 1) F(i, M);
std::cout << k;
return 0;
}
I2luY2x1ZGUgPGlvc3RyZWFtPgoKaW50IGksIGosIGssIEFbMTAwMl1bMTAwMl0sIEJbMTAwMl1bMTAwMl0sIE4sIE07CgppbnQgRihpbnQgeCwgaW50IHkpIHsKICAgIGlmICh4ID09IDAgfHwgeSA9PSAwIHx8IHggPT0gTisxIHx8IHkgPT0gTSsxIHx8IEJbeF1beV0gPT0gMSkgcmV0dXJuIDA7CiAgICBCW3hdW3ldID0gMTsKICAgIC0tazsKICAgIGlmIChBW3gtMV1beV0gPT0gNCkgRih4LTEsIHkpOwogICAgaWYgKEFbeCsxXVt5XSA9PSAyKSBGKHgrMSwgeSk7CiAgICBpZiAoQVt4XVt5LTFdID09IDEpIEYoeCwgeS0xKTsKICAgIGlmIChBW3hdW3krMV0gPT0gMykgRih4LCB5KzEpOwogICAgcmV0dXJuIDA7Cn0KCmludCBtYWluKCkgewogICAgc3RkOjpjaW4gPj4gTiA+PiBN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