1251:仙岛求药

#include<bits/stdc++.h>
using namespace std;
int m, n;
char mp[25][25];
int sx, sy, ex, ey;
struct node{                    //结构体定义位置坐标和起点开始步骤
    int x, y, step;
};
int dir[4][2]={{-1,0},{1,0},{0,-1},{0,1}};        //二维数组定义上下左右方向位移量
node que[10010];    //结构体数组存放队列
int f, r;            //队首和队尾定义
void bfs(){
    int ans=-1;
    f=r=1;            //队列初始化
    que[r].x=sx; que[r].y=sy; que[r].step=0; mp[sx][sy]='#';//初始位置入队
    while(f<=r){
        int fx=que[f].x,   fy=que[f].y, fs=que[f].step;//获取队首信息
        if(fx==ex && fy==ey){//判断是否到达目标
            ans=fs;
            break;
        }
        for(int i=0; i<4; i++){//遍历四个方向
            int nx=fx+dir[i][0];
            int ny=fy+dir[i][1];
            if(nx>=0 && nx<m && ny>=0 && ny<n && (mp[nx][ny]=='.' || mp[nx][ny]=='*')){//判断是否满足入队条件 ,注意此处终点排除‘T’
                mp[nx][ny]='#';//更改状态避免重复入队
                r++;//队尾后移准备入队
                que[r].x=nx;//入队
                que[r].y=ny;
                que[r].step=fs+1;//步骤加1
            }
        }
        f++;//队首后移出队
    }
    cout<<ans<<endl;

}
int main()
{
    while(1){
        cin>>m>>n;
        if(m==0 && n==0)break;
        for(int i=0; i<m; i++)cin>>mp[i];
        for(int i=0; i<m; i++)
            for(int j=0; j<n; j++){
                if(mp[i][j]=='@')sx=i, sy=j;
                if(mp[i][j]=='*')ex=i, ey=j;
            }
        bfs();
    }
    return 0;
 }
原文地址:https://www.cnblogs.com/qwn34/p/13775365.html