#define fi first
#define se second
typedef int type;
typedef pair< int, int > pii;
typedef pair< type, pii > pti;
typedef pair< type, pti > ptpti;
const int maxn = 1e3, maxm = 1e3;
int ar[maxn][maxm];
int ge[maxn][maxm];
const int di[] = {0, -1, 0, 1};
const int dj[] = {-1, 0, 1, 0};
int n, m;
int astar(pii source, pii sink, int k) {
priority_queue< ptpti, vector< ptpti >, greater< ptpti > > srp;
srp.push({ge[source.fi][source.se], {0, source}});
int cnt = 0;
while (!srp.empty()) {
static pti cur;
cur = srp.top().se, srp.pop();
if (cur.se == sink && ++cnt == k) return cur.fi;
for (int t = 0; t < 4; t++) {
static int i, j;
i = cur.se.fi + di[t], j = cur.se.se + dj[t];
if (i >= 0 && i < n && j >= 0 && j < m)
srp.push({ge[i][j] + cur.fi + 1, {cur.fi + 1, {i, j}}});
}
}
return -1; // never
}