int A[1d7],H,W,i,z,t;int f(int i){return A[i]=A[i]-i?f(A[i]):i;}{rd(H,W);rep(j,H*W){rd(t);if(A[i=j%W-j/W*~W-~W]=t*i)rep(k,2)if(t=f(i-1-k*W))A[f(i)]=t;}for(;--i;)z+=i==f(i);wt(z);}