• BFS


    题目:

    代码:

    #include <iostream>
    #include <queue>
    #include <cstring>
    #include <cstdio>
    using namespace std;
     
    char maze[100][100];
    int n,m,bx,by;
    int dx[4]= {0,1,0,-1};
    int dy[4]= {1,0,-1,0};  //定义四个方向
    int vis[100][100];      //标记数组
     
    struct node
    {
        int x,y,step;
    };
    node b;
    queue<node>q;
    int bfs()
    {
        while(!q.empty()){q.pop();}  //清空队列
        memset(vis,0,sizeof(vis));
        b.step=0;               //起点的步数为0
        q.push(b);              //将起点加入队列
      //  vis[b.x][b.y]=1;
        while(!q.empty())       //当队列为空时结束
        {
            node now;           //node now 定义
            now=q.front();      //从队列头部取出元素
            q.pop();            //删除队列头部元素
            if(maze[now.x][now.y]=='G')
                return (now.step);      //如果到终点就返回
            for(int i=0; i<4; i++)      //四个循环表示走向四个方向
            {
                node next;
                next=now;
                next.x+=dx[i];
                next.y+=dy[i];
                next.step++;
                if(maze[next.x][next.y]=='G')
                    return (next.step);            //走到终点
                else if(next.x>=0&&next.x<n&&next.y>=0&&next.y<m&&!vis[next.x][next.y]&&maze[next.x][next.y]=='.')
                {
                    vis[next.x][next.y]=1;
                    q.push(next);                 //没有越界 没有走过 没有撞墙 没有到终点 就加入队列
                }
            }
        }
    }
     
     
    int main()
    {
        freopen("in.txt","r",stdin);
        //freopen("out.txt","w",stdout);
        while(cin>>n>>m)  //输入n,m
        {
            for(int i=0; i<n; i++)
                for(int j=0; j<m; j++)
                {
                    cin>>maze[i][j];    //输入地图
                    if(maze[i][j]=='S')
                    {
                        b.x=i;
                        b.y=j;           // node b是起点的坐标
                        vis[i][j]=1;     //找到起点并把它标记成走过
                    }
                    else if(maze[i][j]=='#')
                        vis[i][j]=1;      //#墙壁表示不能走 也把它标记成走过了
                }
    //        cout<<n<<" "<<m<<endl;
    //        cout<<b.x<<" "<<b.y<<endl;
    //
    //        for(int i=0; i<n; i++)
    //            {for(int j=0; j<m; j++)
    //              cout<<maze[i][j];
    //              cout<<endl;}
     
     
                 cout<<bfs();
        }
        return 0;
    }
  • 相关阅读:
    Cocos2Dx for XNA类解析(1): CCApplication
    struts2动态调用action的方法
    python导出依赖包
    python 字符串split()方法
    struts2使用通配符调用action
    python3重新编译
    Jquery中html()、text()、val()的使用和区别
    Javascript写在<body>和<head>中的区别
    设计模式Design Pattern(2)单例模式
    设计模式Design Pattern(1)简介
  • 原文地址:https://www.cnblogs.com/20172674xi/p/9539786.html
Copyright © 2020-2023  润新知