BFS模板解题 - 1

献给阿尔吉侬的花束

 

算法分析: 

一、使用BFS算法解决二维最短路问题

二、BFS算法关键步骤:

1、初始状态入队

2、取出队头元素

3、拓展新节点

4、新节点入队

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <queue>  // 需使用队列实现bfs

using namespace std;

typedef pair<int,int> PII;  // 使用PII存储坐标
#define x first
#define y second

const int N = 210;

int r,c;
PII start,_end;  // 起点start,终点_end
char g[N][N];    // 存储迷宫地图
int dist[N][N];  // 存储各点到起点start的距离
int dx[4] = {-1,1,0,0};  // 偏移量
int dy[4] = {0,0,-1,1};  // 偏移量

int bfs (PII start,PII _end)  // BFS
{
    queue<PII> q;   // 队列q
    
    // 1、初始状态入队
    q.push(start);  
    
    memset(dist,-1,sizeof dist);
    dist[start.x][start.y] = 0;
    
    while(q.size())  // 当队列q非空时
    {
        // 2、取出队头元素
        PII h = q.front();  
        q.pop();
        
        for(int i=0;i<4;i++)  // 四个方向
            {
                // 3、拓展新节点
                int x = h.x + dx[i];
                int y = h.y + dy[i];
                
                if(x<0 || x>=r || y<0 || y>=c) continue;  // 越界
                if(dist[x][y] != -1) continue;            // 之前已经遍历
                if(g[x][y] == '#') continue;              // 墙壁
                
                dist[x][y] = dist[h.x][h.y] + 1;
                
                if(_end == make_pair(x,y)) return dist[x][y];  // 已经到达终点_end
                
                // 4、新节点入队
                q.push({x,y});
            }
    }
    
    return -1;  // 无法到达终点_end
}

int main()
{
    int T;
    cin >> T;
    
    while(T--)
    {
        cin >> r >> c;
        
        for(int i=0;i<r;i++) scanf("%s",g[i]);
        
        for(int i=0;i<r;i++)
          for(int j=0;j<c;j++)
            if(g[i][j] == 'S') start = {i,j};      // 获取起点start
            else if(g[i][j] == 'E') _end = {i,j};  // 获取终点_end
        
        int d = bfs(start,_end);  // 调用bfs函数
        
        if(d == -1) cout << "oop!" << endl;
        else cout << d <<endl;
    }
    
    return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值