文章

14

粉丝

230

获赞

23

访问

62.3k

头像
迷宫BFS
P1563 天津大学/南开大学2019年机试题
发布于2022年8月10日 09:13
阅读数 4.8k

  1. 利用队列进行广度优先遍历(已经遍历过的需要做标记,尤其是跟结点)
  2. 借助方向数组,遍历4个方向,符合条件,入队
  3. 遍历到终点,退出判断(如果不可能到终点,返回-1,所以设置ans初始值为-1)

代码

#include<bits/stdc++.h>

using namespace std;
const int maxn = 100+5;
char mpt[maxn][maxn];
int vis[maxn][maxn];
int dir[4][2] = {0,1,1,0,0,-1,-1,0};
struct node
{
    int x,y;
    int step;
};
int bfs(int sx,int sy)
{
    memset(vis,0,sizeof(vis));
    queue<node> q;
    q.push(node{sx,sy,0});
    vis[sx][sy]=1;
    int ans=-1;
    while(!q.empty())
    {
        node now = q.front();
        q.pop();
        if(mpt[now.x][now.y]=='E')
        {
            ans =now.step;
            break;
        }
        for(int i=0; i<4; i++)
        {
            int x= now.x+dir[i][0];
            int y = now.y+dir[i][1];

            if((mpt[x][y]=='*'||mpt[x][y]=='E')&&vis[x][y]==0)
            {
                q.push(node{x,y,now.step+1});
                vis[x][y]=1;
            }

        }
    }
    return an...
登录查看完整内容


登录后发布评论

暂无评论,来抢沙发