1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 #include <algorithm> 5 #include <queue> 6 using namespace std; 7 8 struct node 9 { 10 int x,y,step; 11 }; 12 13 char map[105][105]; 14 bool vis[105][105]; 15 int dir[4][2]= {{1,0},{-1,0},{0,1},{0,-1}}; 16 int n,m,sx,sy,ex,ey,ans; 17 18 int check(int x,int y) 19 { 20 if(x<0 || x>=n || y<0 || y>=m) 21 return 1; 22 if(vis[x][y] || map[x][y]=='#') 23 return 1; 24 return 0; 25 } 26 27 void bfs() 28 { 29 int i; 30 queue<node> q; 31 node a,next; 32 a.x = sx; 33 a.y = sy; 34 a.step = 0; 35 vis[a.x][a.y]=true; 36 q.push(a); 37 while(!q.empty()){ 38 a = q.front(); 39 q.pop(); 40 if(map[a.x][a.y]=='E'){ 41 ans = a.step; 42 return ; 43 } 44 for(i = 0;i < 4; i++){ 45 next.x = a.x + dir[i][0]; 46 next.y = a.y + dir[i][1]; 47 if(check(next.x,next.y)) continue; 48 next.step = a.step + 1; 49 vis[next.x][next.y] = true; 50 q.push(next); 51 } 52 } 53 ans = -1; 54 } 55 56 int main() 57 { 58 int t; 59 cin>>t; 60 while(t--){ 61 cin>>n>>m; 62 for(int i = 0;i < n;i++) 63 scanf("%s",map[i]); 64 for(int i = 0;i < n;i++){ 65 for(int j = 0;j < m;j++){ 66 if(map[i][j]=='S'){ 67 sx = i; 68 sy = j; 69 } 70 } 71 } 72 memset(vis,0,sizeof(vis)); 73 bfs(); 74 cout<<ans<<endl; 75 } 76 return 0; 77 }