详解:http://blog.csdn.net/ac_hell/article/details/51097666
#include <cstdio>
#include <cstring>
#include <iostream>
#include <queue>
using namespace std;
#define maxn 50
char mp[maxn][maxn];
int n , m;
int sx,sy;
int ex,ey;
int way[4][2] = {0,-1 , -1,0 , 0,1 , 1,0};
int vis[maxn][maxn];
struct node
{
int x,y;
int step;
};
bool judge(int x,int y)
{
if( mp[x][y] == '.' && !vis[x][y] ){
return 1;
}
return 0;
}
int dfs(int x,int y,int q,int kase)
{
if( x == ex && y == ey )
return 1;
int res = 0;
for(int i = q + kase ; i < q + kase + 4*(4-kase) ; i += (4-kase))
{
int k = i%4 ;
int nx = x + way[k][0];
int ny = y + way[k][1];
if( judge(nx,ny) )
{
res = dfs(nx, ny, k , kase) + 1;
break;
}
}
return res;
}
int bfs()
{
node s;
s.x = sx;
s.y = sy;
s.step = 1;
queue<node>Q;
Q.push(s);
while(!Q.empty())
{
node e = Q.front();
Q.pop();
if( e.x == ex && e.y == ey )return e.step;
for(int i = 0 ; i < 4 ; ++i)
{
node nx = e;
nx.x += way[i][0];
nx.y += way[i][1];
nx.step++;
if( judge(nx.x,nx.y) )
{
Q.push(nx);
vis[nx.x][nx.y] = 1;
}
}
}
}
int main()
{
int T;
cin >> T;
while( T-- )
{
memset(vis,0,sizeof(vis));
cin >> m >> n;
for (int i = 1; i <= n; i++)
for (int j = 1; j <= m; j++)
{
cin >> mp[i][j];
if (mp[i][j] == 'S') { sx = i, sy = j; mp[i][j] = '.'; }
if (mp[i][j] == 'E') { ex = i, ey = j; mp[i][j] = '.'; }
}
int q = 0 ;
int ans1 = dfs( sx,sy,q,3 );
int ans2 = dfs( sx,sy,q,1 );
int ans3 = bfs();
cout << ans1 << " " << ans2 << " " << ans3 << endl;
}
}