关于守卫的处理我一直wa,最后愣是把bfs重写了一遍. 把守卫压入队列之前不用管他是否是'r'或者'x',当他从队列弹出时队x进行特殊处理. #include<iostream> #include<cstdio> #include<cstring> #include<queue> struct point { int x,y; int ceng; }start,e,t; int dir[4][2]={1,0,-1,0,0,1,0,-1}; char mat[202][202]; int used[202][202]; int main(void) { int n,m; int i,j; std::queue<struct point> q; while( scanf("%d%d",&n,&m) == 2 ) { for( i = 1; i <= n; i++ ) scanf("%s",mat[i]+1); for( i = 0; i <= n + 1; i++ ) mat[i][0]=mat[i][m+1]='#'; for( i = 0; i <= m + 1; i++ ) mat[0][i]=mat[n+1][i]='#'; for( i = 1; i <= n; i++ ) for( j = 1; j <= m; j++ ) if( mat[i][j] == 'a' ) {start.x=i;start.y=j;start.ceng=0;} memset(used,0,sizeof(used)); q.push(start); used[start.x][start.y] = 1; while( !q.empty() ) { e = q.front();q.pop(); if( mat[e.x][e.y] == 'r' ) break; if( mat[e.x][e.y] == 'x' ) { e.ceng++; mat[e.x][e.y] = '.'; q.push(e); continue; } for( i = 0; i < 4; i++ ) { t = e; t.x += dir[i][0]; t.y += dir[i][1]; t.ceng++; if( !used[t.x][t.y] && mat[t.x][t.y] != '#' ) { used[t.x][t.y]=1; q.push(t); } } } while( !q.empty() ) q.pop(); if( mat[e.x][e.y] == 'r' ) printf("%d/n",e.ceng); else printf("Poor ANGEL has to stay in the prison all his life./n"); } return 0; }