/*
For this one, it is easily to know, it need use the dijkstra way to do that, So we need
to do two things, the first it is turn the data to the AM, and use AM data to do the
dijkstra way.And in dijkstra Algorithm, it need to create two arrays, the one is the array
to determine the point is read or not, if it is read, we don’t change its value. The second
is storing the distance from origin point to their location.
-
/
import java.util.;
public class Maze{
private static final int INF = 999999;
public static int[][] transfer(int maze1[],int M, int N) {
int[][] Matrix1 = new int[M * N][M * N];
for (int i1 = 0; i1 < M * N; i1++) {
for (int i2 = 0; i2 < M * N; i2++) {
Matrix1[i1][i2] = 999999;
Matrix1[i1][i1] = 0;
if(i1-M>= 0)
Matrix1[i1][i1-M]=maze1[i1];
if(i1+M<MN)
Matrix1[i1][i1+M]=maze1[i1+M];
if(i1+1<MN)
Matrix1[i1][i1+1]=maze1[i1+1];
if(i1-1>=0)
Matrix1[i1][i1-1]=maze1[i1];
}
}
return Matrix1;
}public static void dijkstra(int Matrix[][],int M, int N){
boolean[] isVisited = new boolean[MN];
int [] dist = new int[MN];
for(int i = 0; i<MN;i++){
isVisited[i] = false;
dist[i] = Matrix[0][i];
}
isVisited[0] = true;
dist[0] = 0;
int k = 0;
for(int i = 1; i<MN;i++){
int min = INF;
for(int j1=0;j1<MN;j1++) {
if(isVisited[j1]==false && dist[j1]<min){
min = dist[j1];
k = j1;
}
}
isVisited[k] = true;
for(int j2 = 0; j2< MN;j2++){
int tmp = (Matrix[k][j2]==INF ? INF:(min+Matrix[k][j2]));
if(isVisited[j2] == false &&(tmp<dist[j2])){
dist[j2] = tmp;
}
}
}/*
for(int i4 = 0;i4<isVisited.length ;i4++){
boolean k1 = isVisited[i4];
System.out.print(k1);
}/
System.out.println(dist[MN-1]);
}public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
int mazeNumber = scanner.nextInt();
for(int i=0; i<mazeNumber;i++){
int N = scanner.nextInt();
int M = scanner.nextInt();
int[][] maze = new int[N][M];
int[]maze1 = new int[M*N];
for(int i1 = 0; i1<N;i1++){
for(int i2=0; i2<M;i2++){
maze1[i2] = scanner.nextInt();
}
}
int [][]Matrix2 =transfer(maze1,M,N);
dijkstra(Matrix2,M,N);
}}
}