#include <iostream>
int i, j, k, A[1000][1000], B[1000][1000], N, M;
int F(int x, int y) {
if (x == 0 && y == 0 && (A[x][y] == 2 || A[x][y] == 3) ||
x == 0 && y == M-1 && (A[x][y] == 1 || A[x][y] == 2) ||
x == N-1 && y == M-1 && (A[x][y] == 1 || A[x][y] == 4) ||
x == N-1 && y == 0 && (A[x][y] == 3 || A[x][y] == 4) ||
x == 0 && A[x][y] == 2 ||
x == N-1 && A[x][y] == 4 ||
y == 0 && A[x][y] == 3 ||
y == M-1 && A[x][y] == 1) return 0;
B[x][y] = 1;
if (A[x][y] == 1) {
if (B[x][y+1] == 1) return 1;
else return F(x, y+1);
}
if (A[x][y] == 2) {
if (B[x-1][y] == 1) return 1;
else return F(x-1, y);
}
if (A[x][y] == 3) {
if (B[x][y-1] == 1) return 1;
else return F(x, y-1);
}
if (A[x][y] == 4) {
if (B[x+1][y] == 1) return 1;
else return F(x+1, y);
}
return 0;
}
int main() {
std::cin >> N >> M;
k = N*M;
for (i=0; i<N; ++i)
for (j=0; j<M; ++j)
std::cin >> A[i][j];
for (k=i=0; i<N; ++i) {
for (j=0; j<M; ++j) {
k += F(i, j);
for (int i=0; i<N; ++i) {
for (int j=0; j<M; ++j) {
B[i][j] = 0;
}
}
}
}
std::cout << k;
return 0;
}
I2luY2x1ZGUgPGlvc3RyZWFtPgoKaW50IGksIGosIGssIEFbMTAwMF1bMTAwMF0sIEJbMTAwMF1bMTAwMF0sIE4sIE07CgppbnQgRihpbnQgeCwgaW50IHkpIHsKICAgIGlmICh4ID09IDAgJiYgeSA9PSAwICYmIChBW3hdW3ldID09IDIgfHwgQVt4XVt5XSA9PSAzKSB8fCAKICAgICAgICB4ID09IDAgJiYgeSA9PSBNLTEgJiYgKEFbeF1beV0gPT0gMSB8fCBBW3hdW3ldID09IDIpIHx8IAogICAgICAgIHggPT0gTi0xICYmIHkgPT0gTS0xICYmIChBW3hdW3ldID09IDEgfHwgQVt4XVt5XSA9PSA0KSB8fAogICAgICAgIHggPT0gTi0xICYmIHkgPT0gMCAmJiAoQVt4XVt5XSA9PSAzIHx8IEFbeF1beV0gPT0gNCkgfHwKICAgICAgICB4ID09IDAgJiYgQVt4XVt5XSA9PSAyIHx8CiAgICAgICAgeCA9PSBOLTEgJiYgQVt4XVt5XSA9PSA0IHx8CiAgICAgICAgeSA9PSAwICYmIEFbeF1beV0gPT0gMyB8fAogICAgICAgIHkgPT0gTS0xICYmIEFbeF1beV0gPT0gMSkgcmV0dXJuIDA7CiAgICBCW3hdW3ldID0gMTsKICAgIGlmIChBW3hdW3ldID09IDEpIHsKICAgICAgICBpZiAoQlt4XVt5KzFdID09IDEpIHJldHVybiAxOwogICAgICAgIGVsc2UgcmV0dXJuIEYoeCwgeSsxKTsKICAgIH0KICAgIGlmIChBW3hdW3ldID09IDIpIHsKICAgICAgICBpZiAoQlt4LTFdW3ldID09IDEpIHJldHVybiAxOwogICAgICAgIGVsc2UgcmV0dXJuIEYoeC0xLCB5KTsKICAgIH0KICAgIGlmIChBW3hdW3ldID09IDMpIHsKICAgICAgICBpZiAoQlt4XVt5LTFdID09IDEpIHJldHVybiAxOwogICAgICAgIGVsc2UgcmV0dXJuIEYoeCwgeS0xKTsKICAgIH0KICAgIGlmIChBW3hdW3ldID09IDQpIHsKICAgICAgICBpZiAoQlt4KzFdW3ldID09IDEpIHJldHVybiAxOwogICAgICAgIGVsc2UgcmV0dXJuIEYoeCsxLCB5KTsKICAgIH0KICAgIHJldHVybiAwOwp9CgppbnQgbWFpbigpIHsKICAgIHN0ZDo6Y2luID4+IE4gPj4gTTsKICAgIGsgPSBOKk07CiAgICBmb3IgKGk9MDsgaTxOOyArK2kpIAogICAgICAgIGZvciAoaj0wOyBqPE07ICsraikKICAgICAgICAgICAgc3RkOjpjaW4gPj4gQVtpXVtqXTsKICAgIAogICAgZm9yIChrPWk9MDsgaTxOOyArK2kpIHsKICAgICAgICBmb3IgKGo9MDsgajxNOyArK2opIHsKICAgICAgICAJayArPSBGKGksIGopOwogICAgICAgICAgICBmb3IgKGludCBpPTA7IGk8TjsgKytpKSB7CiAgICAgICAgICAgICAgICBmb3IgKGludCBqPTA7IGo8TTsgKytqKSB7CiAgICAgICAgICAgICAgICAgICAgQltpXVtqXSA9IDA7CiAgICAgICAgICAgICAgICB9CiAgICAgICAgICAgIH0KICAgICAgICB9CiAgICB9CiAgICBzdGQ6OmNvdXQgPDwgazsKICAgIHJldHVybiAwOwp9