http://tyvj.cn/p/1117
做BFS,但是不能走到#时直接加2,这样得不出最优时间,需要把#当做两个格子来走,即走完#将他更改为^,入队时仍然入head的x,y,然后在没有加上坐标之前判断是不是^,是的话把它更改为通路“.”,再次入队。
参考代码
#include<cstdio>
struct sb {
int x,y,time;
};
sb hs[10000];
int pre[10000];
const int dx[4] = {1,0,-1,0},
dy[4] = {0,1,0,-1};
int t,x,y;
int mx,my,sx,sy;
char map[30][30];
void init () {
scanf("%d%d%d\n", &t, &y, &x);
int i,j;
for (i=0;i<x;i++) {
gets(map[i]);
for (j=0;j<y;j++) {
if (map[i][j]=='m') {
mx = i, my = j;
}
if (map[i][j]=='s') {
sx = i, sy = j;
}
}
}
}
void bfs() {
int i;
int head=0, tail=1;
hs[1].x = sx, hs[1].y = sy, hs[1].time = 0; pre[0]=0;
do {
head++;
if (map[hs[head].x][hs[head].y] == '^') {
tail++;
hs[tail].x = hs[head].x;
hs[tail].y = hs[head].y;
hs[tail].time = hs[head].time+1;
map[hs[head].x][hs[head].y] = '.';
pre[tail] = head;
} else
for (i=0;i<4;i++) {
int cx = hs[head].x + dx[i], cy = hs[head].y + dy[i];
if (cx >= 0 && cy >=0 && cx < x && cy < y) {
if (map[cx][cy] == '.') {
tail++;
hs[tail].x = cx;
hs[tail].y = cy;
hs[tail].time = hs[head].time+1;
map[cx][cy] = 'o';
pre[tail] = head;
}
if (map[cx][cy] == '#') {
tail++;
hs[tail].x = cx;
hs[tail].y = cy;
hs[tail].time = hs[head].time+1;
map[cx][cy] = '^';
pre[tail] = head;
}
if (map[cx][cy] == 'm') {
if (hs[head].time+1<t) {
printf("%d\n", hs[head].time+1);
} else printf("55555\n");
return;
}
}
}
} while(head<tail);
}
int main() {
init();
bfs();
return 0;
}