#include <iostream>
#include <algorithm>
#include <queue>
#include <math.h>
#include <climits>
#include <map>
using namespace std;
int n;
int buffer[101][101];
int l;
int main(){
cin.tie(NULL);
ios::sync_with_stdio(false);
cin >> n >> l;
for (auto x=0; x<n; x++){
for (auto y=0; y<n; y++){
cin >> buffer[x][y];
}
}
int count = 0;
for (auto x=0; x<n; x++){
vector<pair<int, int>> v;
for (auto y=0; y<n; y++){
if (v.size() == 0){
v.push_back(make_pair(buffer[x][y], 1));
}else if (v.back().first == buffer[x][y]){
v.back().second++;
}else {
v.push_back(make_pair(buffer[x][y], 1));
}
}
if (v.size() == 1){
count++;
} else {
for (auto i=1; i<v.size(); i++){
if ( abs (v[i].first- v[i-1].first) != 1 ){
goto Fail;
} else {
auto v1 = v[i];
auto v2 = v[i-1];
if ( v1.first > v2.first){
if (v2.second >= l){
v[i-1].second -= l;
}else {
goto Fail;
}
}else {
if (v1.second >= l){
v[i].second -= l;
}else {
goto Fail;
}
}
}
}
count++;
Fail:;
}
}
for (auto y=0; y<n; y++){
vector<pair<int, int>> v;
for (auto x=0; x<n; x++){
if (v.size() == 0){
v.push_back(make_pair(buffer[x][y], 1));
}else if (v.back().first == buffer[x][y]){
v.back().second++;
}else {
v.push_back(make_pair(buffer[x][y], 1));
}
}
if (v.size() == 1){
count++;
} else {
for (auto i=1; i<v.size(); i++){
if ( abs (v[i].first- v[i-1].first) != 1 ){
goto Fail_2;
} else {
auto v1 = v[i];
auto v2 = v[i-1];
if ( v1.first > v2.first){
if (v2.second >= l){
v[i-1].second -= l;
}else {
goto Fail_2;
}
}else {
if (v1.second >= l){
v[i].second -= l;
}else {
goto Fail_2;
}
}
}
}
count++;
Fail_2:;
}
}
cout << count;
return 0;
}