单点时限: 2.0 sec
内存限制: 256 MB
小强生日就要到了,partychen 为了送给小强一个特别的礼物,决定到恶魔之城去偷走他们的镇城之宝:月亮之石。partychen 已经从江湖百晓生处得到了恶魔之城的地图。根据地图的描述,恶魔之城是一个标准的 大小的一个悬在空中的城堡,里面有可以走的路,也有一些陷阱,如果人踏入陷阱那么将被恶魔吃掉,如果不小心踏出这个城堡,那么就将尸骨无存。partychen 去城之前买了两个传送,第一个传送将把 partychen 安全的送往入口。第二个在拿到月亮之石的地方使用,安全的把 partychen 送回地面。由于时间紧迫,partychen 能力有限,希望天才的你帮助他计算一下从入口安全到达到月亮之石的所在地最快需要多少步。并且帮他算出应该怎么走步数最小。当然可能有很多种走法,你只要输出任意可行的一种就可以了。
输入格式
第一行 2 个数 (),代表城的长和宽,因此城的左上角坐标为 ,右下角的坐标为 。然后 行,每行 个字符:
S 代表城的入口;
E 代表月亮之石的地方;
- 代表陷阱,一旦走进去将被恶魔吃掉;
. 代表安全的路。
输出格式
如果不能安全达到出口就输出 。
如果能够安全到达出口,第一行输出最小的步数 。后面 行输出从入口到达月亮之石的所在地的路径,每行两个整数代表该点的坐标。(包括起点和终点坐标)
样例
input
4 4
S…
…
…*.
…E
output
6
0 0
0 1
1 1
2 1
3 1
3 2
3 3
提示
partychen 从 S 到达 E,需要 6 步:(0,0)–>(0,1)–>(1,1)–>(2,1)–>(3,1)–>(3,2)–>(3,3)
/*
思路:bfs+路径保存
*/
#include<iostream>
#include<queue>
#include<vector>
using namespace std;
int n,m;
int xx[4]= {0,0,1,-1};
int yy[4]= {1,-1,0,0};
char s[200][200];
int flag=0;
struct node {
int x,y;
};
int x1,x2,y1,y2;
vector<node>v;
node path[200][200];//保存上一顶点的坐标
void bfs() {
node t= {x1,y1};
s[x1][y1]='*';
queue<node>q;
q.push(t);
while(!q.empty()) {
node f = q.front();
q.pop();
if(f.x==x2&&f.y==y2) {
while(f.x!=x1||f.y!=y1) {
v.push_back(f);
f=path[f.x][f.y];
}
v.push_back(f);
cout<<v.size()-1<<endl;
flag=1;
for(int i = v.size()-1; i >=0; i--) {
cout<<v[i].x<<" "<<v[i].y<<endl;
}
return ;
} else
for(int i = 0; i < 4; i++) {
int a=xx[i]+f.x;
int b=yy[i]+f.y;
if(a>=0&&a<n&&b>=0&&b<m&&s[a][b]!='*') {
node m= {a,b};
s[a][b]='*';
path[a][b]=f;
q.push(m);
}
}
}
}
int main() {
cin>>n>>m;
for(int i =0; i < n; i++) {
for(int j = 0; j < m; j++) {
cin>>s[i][j];
if(s[i][j]=='S') {
x1=i;
y1=j;
}
if(s[i][j]=='E') {
x2=i;
y2=j;
}
}
}
bfs();
if(flag==0)
cout<<-1;
return 0;
}