起点 S到终点T的步数
输入:
5 5
.....
.*.*.
.*S*.
.***.
...T*
2 2 4 3
  输出
11
  #include <iostream>
#include <cstdio>
#include <cstdlib>
#include <queue>
#include <cstring>
using namespace std;
const int maxn=100;
typedef struct{
    int x,y;        //坐标 
    int step;       //step 为从起点S到达该位置的最小步数 
}Node;
Node S,T,node;      //S为起点,T为终点,node为临时结点 
int n,m;
char maze[maxn][maxn];
bool inq[maxn][maxn];
int X[4]={
  0,0,1,-1};
int Y[4]={
  1,-1,0,0};
//检测坐标是否有效
bool test(int x,int y)
{
    //越界,false 
    if(x>=n || x<0 || y>=m || y<0  )
    {
        return false;
    }
    //碰墙,false;已经 入过队,false 
    if( maze[x][y]=='*' || inq[x][y]==true  )
    {
        return false;
    }
    return true;
} 
int  BFS()
{
    //定义队列 
    queue<Node> queue;
    //将起点S 入队列 
    queue.push(S);
    while(!queue.empty())
    {
        Node top=queue.front();
        queue.pop();
        if( top.x==T.x && top.y==T.y )
        {
            return top.step;
        }
        for(int i=0;i<4;i++)
        {
            int newx=top.x+X[i];
            int newy=top.y+Y[i];
            if(test(newx,newy)  )
            {
                node.x=newx;
                node.y=newy;
                node.step=top.step+1;
                queue.push(node);
                inq[newx][newy]=true;
            }
        }
    }
    return -1;
}
int main()
{
    scanf("%d %d",&n,&m);
    for(int i=0;i<n;i++)
    {
        getchar();      //过滤掉每行之后的换行符 
        for(int j=0;j<m;j++)
        {
            maze[i][j]=getchar(); 
        }
        maze[i][m+1]='\0'; 
    }
    //初始化起点和终点的坐标 
    scanf("%d%d%d%d",&S.x,&S.y,&T.x,&T.y);
    S.step=0;   //初始化起点的层数为0,即S到S的最少步数是0 
    printf("%d\n",BFS());
    return 0;
}

京公网安备 11010502036488号