#include <bits/stdc++.h>
using namespace std;
const int MAX = 507;
const int INF = 1007;
int n, k;
char S[MAX][MAX];
int R[MAX][MAX][51];
int main()
{
cin >> n >> k;
for(int i = 0; i < n; i++)
cin >> S[i];
for(int i = 0; i <= n; i++)
for(int j = 0; j <= n; j++)
for(int c = 0; c <= k; c++)
R[i][j][c] = INF;
int res = INF;
for(int i = 0; i < n; i++)
for(int j = 0; j < n; j++)
{
R[i][j][0] = 0;
R[i][j][S[i][j]-'0'] = min(R[i][j][S[i][j]-'0'], 1);
for(int c = 0; c <= k; c++)
{
if (c == k)
res = min(res, R[i][j][c]);
if (i+1 < n)
R[i+1][j][min(k, c+S[i+1][j]-'0')] = min(R[i+1][j][min(k, c+S[i+1][j]-'0')], R[i][j][c]+1);
if (j+1 < n)
R[i][j+1][min(k, c+S[i][j+1]-'0')] = min(R[i][j+1][min(k, c+S[i][j+1]-'0')], R[i][j][c]+1);
}
}
if (res >= INF)
res = -1;
cout << res << endl;
return 0;
}