#include <cstdio>
#include <cstdlib>
struct pt{ int x, y; pt(int _x = 0, int _y =0){x = _x, y = _y;}};
int main(){
int T; scanf("%d", &T);
while(T--){
int n,m; scanf("%d %d", &n, &m);
int tab[200][200];
for(int lx = 0;lx < n; lx++)
for(int ly = 0;ly < m;ly++)
scanf("%d", &tab[lx][ly]);
pt que[400];
int qs = 0, qe = 0;
int rad[200][200];
for(int lx = 0;lx < n;lx++)
for(int ly = 0;ly < m;ly++)
rad[lx][ly] = 500;
rad[0][0] = 0;
que[qe++] = pt(0, 0);
int dx[] = {0, 0, 1, -1}, dy[] = {1, -1, 0, 0};
while(qe > qs){
pt prc = que[qs++];
int px = prc.x, py = prc.y;
for(int w = 0;w < 4;w++){
int nx = px + dx[w], ny = py + dy[w];
if(nx < 0 or nx >= n or ny < 0 or ny >= m) continue;
if(abs(tab[nx][ny] - tab[px][py]) > 5) continue;
if(rad[nx][ny] != 500) continue;
rad[nx][ny] = rad[px][py] + 1;
que[qe++] = pt(nx, ny);
}
}
printf("%d\n", rad[n-1][m-1]);
}
return 0;
}
沒有留言:
張貼留言