BFS 模板 【迷宫的最短路径】

简介:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cmath>
#include <vector>
#include <queue>
#include <algorithm>
#include <set>
#include <stack>
using namespace std;

#define MM(a) memset(a,0,sizeof(a))

typedef long long LL;
typedef unsigned long long ULL;
const int maxn = 2*1e3+5;
const int INF = 1e9+5;
const int mod = 1000000007;
const double eps = 1e-7;

struct node
{
    int x, y, step;
};

char map[105][105];
bool vis[105][105];
int dx[4] = {1, -1, 0, 0};
int dy[4] = {0, 0, -1, 1};
int n, m;
int sx, sy, ex, ey;
int ans;

bool check(int x,int y)
{
    if(x<0 || x>=n || y<0 || y>=m)
        return 1;
    if(vis[x][y] || map[x][y]=='#')
        return 1;
    return 0;
}

void bfs()
{
    queue<node> Q;
    node a, next;
    a.x = sx;
    a.y = sy;
    a.step = 0;
    vis[a.x][a.y] = 1;
    Q.push(a);
    while(!Q.empty())
    {
        a = Q.front();
        Q.pop();
        if(map[a.x][a.y]=='E')
        {
            ans = a.step;
            return ;
        }
        for(int i=0; i<4; i++)
        {
            next = a;
            next.x += dx[i];
            next.y += dy[i];
            if(check(next.x,next.y))
                continue;
            next.step = a.step+1;
            vis[next.x][next.y] = 1;
            Q.push(next);
        }
    }
    ans = -1;
}

int main()
{
    int t;
    scanf("%d",&t);
    while(t--)
    {
        scanf("%d%d",&n,&m);
        for(int i=0; i<n; i++)
            scanf("%s",map[i]);
        for(int i=0; i<n; i++)
        {
            for(j=0; j<m; j++)
            {
                if(map[i][j] == 'S')
                {
                    sx = i;
                    sy = j;
                }
            }
        }
        MM(vis);
        bfs();
        printf("%d\n",ans);
    }
    return 0;
}

目录
相关文章
|
4月前
|
存储 算法
使用 BFS 解决走迷宫问题
使用 BFS 解决走迷宫问题
37 1
|
4月前
|
算法 Java C++
走迷宫(BFS)
走迷宫(BFS)
27 0
|
7月前
|
机器学习/深度学习 算法 测试技术
C++算法:01BFS最短距离的原理和实现
C++算法:01BFS最短距离的原理和实现
|
7月前
|
算法 Python
使用深度优先搜索算法解决迷宫问题
迷宫问题是一个经典的算法问题,涉及到通过一个迷宫找到从起点到终点的路径。在本篇博客中,我们将探讨如何使用深度优先搜索(DFS)算法来解决迷宫问题。
208 2
|
10月前
|
Java
BFS广度优先遍历——Acwing 844. 走迷宫
BFS广度优先遍历——Acwing 844. 走迷宫
53 0
|
11月前
|
定位技术
BFS:迷宫最短路径
BFS:迷宫最短路径
|
存储 算法
秒懂算法 | BFS与最短路径
搜索包括BFS和DFS,这两种算法是算法竞赛的基础。本篇介绍BFS的扩展应用。
379 0
秒懂算法 | BFS与最短路径
|
定位技术 C++
基于c++深度优先遍历迷宫
基于c++深度优先遍历迷宫
103 0
基于c++深度优先遍历迷宫
|
存储
【每日一题Day61】寻找图中是否存在路径 | BFS 并查集
初始时将source设为已访问,并且将其加入队列。之后每次将队列中的节点出队,并将其能够到达的未访问过的节点入队。如果访问到destination,则直接返回true;如果队列为空,仍未访问到destination,则返回false
88 0
|
定位技术
深搜dfs 解决全排列,地图搜索最短距离
深搜dfs 解决全排列,地图搜索最短距离