迷宫的最短路径 -- 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;

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

typedef pair <int, int> P;
void Init()
{
    for(int i=0; i<n; i++)
    {
        for(int j=0; j<m; j++)
        {
            dis[i][j] = INF;
        }
    }
}
int BFS()
{
    queue<P> que;
    Init();
    que.push(P(sx,sy));
    dis[sx][sy] = 0;
    while(que.size())
    {
        P p = que.front();
        que.pop();
        if(p.first==ex && p.second==ey)
            break;
        for(int i=0; i<4; i++)
        {
            int nx = p.first+dx[i];
            int ny = p.second+dy[i];
            if(nx>=0 && nx<n && ny>0 && ny<m && map[nx][ny]!='#' &&
               dis[nx][ny]==INF)
            {
                que.push(P(nx, ny));
                dis[nx][ny] = dis[p.first][p.second]+1;
            }
        }
    }
    return dis[ex][ey];
}
int main()
{
    while(cin>>n>>m)
    {
        for(int i=0; i<n; i++)
            cin>>map[i];
        for(int i=0; i<n; i++)
        {
            for(int j=0; j<m; j++)
            {
                if(map[i][j] == 'S')
                {
                    sx = i;
                    sy = j;
                }
                if(map[i][j] == 'E')
                {
                    ex = i;
                    ey = j;
                }
            }
        }
        printf("%d\n",BFS());
    }
    return 0;
}
/**
#S######.#
......#..#
.#.##.##.#
.#........
##.##.####
....#....#
.#######.#
....#.....
.####.###.
....#...E#
**/

目录
相关文章
|
3月前
|
算法
最短路之Dijkstra算法
最短路之Dijkstra算法
24 0
|
3月前
|
存储 算法
使用 BFS 解决走迷宫问题
使用 BFS 解决走迷宫问题
36 1
|
3月前
|
算法 Java C++
走迷宫(BFS)
走迷宫(BFS)
26 0
|
4月前
|
C++
|
4月前
|
机器学习/深度学习 编解码 算法
|
6月前
|
机器学习/深度学习 算法 测试技术
C++算法:01BFS最短距离的原理和实现
C++算法:01BFS最短距离的原理和实现
|
10月前
|
定位技术
BFS:迷宫最短路径
BFS:迷宫最短路径
|
存储 算法
秒懂算法 | BFS与最短路径
搜索包括BFS和DFS,这两种算法是算法竞赛的基础。本篇介绍BFS的扩展应用。
373 0
秒懂算法 | BFS与最短路径
|
机器学习/深度学习 定位技术