#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define dbg(x) cout << #x << " : " << x << endl
#define rep(i, a, b) for (int i = (a); i <= (b); i++)
#define inf 1000000000000000000
priority_queue<ll, vector<ll>, greater<int>> qp;
priority_queue<ll> qr;
#define maxn 705
#define mod 1000000007
ll dx[8] = {-1, -1, -1, 0, 1, 1, 1, 0};
ll dy[8] = {-1, 0, 1, 1, 1, 0, -1, -1};
/**************TEMPLATES**********************/
ll n, m;
ll a[maxn][maxn], dau[maxn][maxn], res[maxn][maxn];
struct node
{
ll x, y;
};
bool check(ll fi, ll se)
{
if (0 > fi || 0 > se || fi >= n || se >= m)
return true;
return false;
}
bool cmp(pair<ll,node> A, pair<ll,node> B){
if(A.first==B.first) return A.second.x>B.second.x;
return A.first>B.first;
}
vector<pair<ll, node>> vt;
void dfs(node source)
{
dau[source.x][source.y]=1;
for(ll i=0;i<8;i++){
node tmp;
tmp.x = source.x + dx[i];
tmp.y = source.y + dy[i];
if(check(tmp.x,tmp.y)) continue;
if(dau[tmp.x][tmp.y]==1) continue;
if(a[tmp.x][tmp.y]<=a[source.x][source.y]) dfs(tmp);
}
}
int main()
{
// freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
cin >> n >> m;
ll i, j;
for (i = 0; i < n; i++)
for (j = 0; j < m; j++)
{
cin >> a[i][j];
node tmp;
tmp.x = i;
tmp.y = j;
vt.push_back({a[i][j], tmp});
}
sort(vt.begin(),vt.end(),cmp);
ll ans=0;
for(auto p: vt){
if(dau[p.second.x][p.second.y]==1) continue;
ans++;
node source;
source.x = p.second.x;
source.y = p.second.y;
dfs(source);
}
// cout<<1;
cout<<ans;
return 0;
}
I2luY2x1ZGUgPGJpdHMvc3RkYysrLmg+CnVzaW5nIG5hbWVzcGFjZSBzdGQ7CiNkZWZpbmUgbGwgbG9uZyBsb25nCiNkZWZpbmUgZGJnKHgpIGNvdXQgPDwgI3ggPDwgIiA6ICIgPDwgeCA8PCBlbmRsCiNkZWZpbmUgcm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AueSA9IHNvdXJjZS55ICsgZHlbaV07CiAgICAgICAgaWYoY2hlY2sodG1wLngsdG1wLnkpKSBjb250aW51ZTsKICAgICAgICBpZihkYXVbdG1wLnhdW3RtcC55XT09MSkgY29udGludWU7CiAgICAgICAgaWYoYVt0bXAueF1bdG1wLnldPD1hW3NvdXJjZS54XVtzb3VyY2UueV0pIGRmcyh0bXApOwogICAgfQp9CmludCBtYWluKCkKewogICAgLy8gZnJlb3BlbigiaW5wdXQudHh0IiwgInIiLCBzdGRpbik7CiAgICAvLyBmcmVvcGVuKCJvdXRwdXQudHh0IiwgInciLCBzdGRvdXQpOwogICAgY2luID4+IG4gPj4gbTsKICAgIGxsIGksIGo7CiAgICBmb3IgKGkgPSAwOyBpIDwgbjsgaSsrKQogICAgICAgIGZvciAoaiA9IDA7IGogPCBtOyBqKyspCiAgICAgICAgewogICAgICAgICAgICBjaW4gPj4gYVtpXVtqXTsKICAgICAgICAgICAgbm9kZSB0bXA7CiAgICAgICAgICAgIHRtcC54ID0gaTsKICAgICAgICAgICAgdG1wLnkgPSBqOwogICAgICAgICAgICB2dC5wdXNoX2JhY2soe2FbaV1bal0sIHRtcH0pOwogICAgICAgIH0KICAgIHNvcnQodnQuYmVnaW4oKSx2dC5lbmQoKSxjbXApOwogICAgbGwgYW5zPTA7CiAgICBmb3IoYXV0byBwOiB2dCl7CiAgICAgICAgaWYoZGF1W3Auc2Vjb25kLnhdW3Auc2Vjb25kLnldPT0xKSBjb250aW51ZTsKICAgICAgICBhbnMrKzsKICAgICAgICBub2RlIHNvdXJjZTsKICAgICAgICBzb3VyY2UueCA9IHAuc2Vjb25kLng7CiAgICAgICAgc291cmNlLnkgPSBwLnNlY29uZC55OwogICAgICAgIGRmcyhzb3VyY2UpOwogICAgfQogICAgLy8gY291dDw8MTsKICAgIGNvdXQ8PGFuczsKICAgIHJldHVybiAwOwp9