[bfs] Saving Tang Monk II hihocode1828

本文深入探讨了BFS算法在实战中常见的错误与优化策略,通过具体案例分析,指出在使用优先队列实现BFS时,终点处理不当可能导致的时间复杂度问题。强调了正确的终点检测时机对于算法效率的重要性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题意

题目链接

题解

这本来是一道简单的bfs题,但自己平时代码习惯不好,导致比赛时T了还找不出原因(手动幽灵)。

主要原因是bfs返回位置不对。如果用优先队列做,从将终点进队到将终点出队会间隔很多个点。所以应该在将终点进队时就返回!谨记谨记!

代码

#include <cstdio>
#include <queue>
#include <cstring>
#include <vector>
#include <functional>
#include <algorithm>
#include <unordered_map>
#include <string>
#include <iostream>
using namespace std;

typedef long long ll;

const int maxn = 100+1;
const int INF = 0x3f3f3f3f;
const int dx[] = {0,0,-1,1};
const int dy[] = {-1,1,0,0};

struct pt{
    int x,y;
    int oxy;
    int time;
    pt(int x=0, int y=0, int o=0,int t=0):x(x),y(y),oxy(o),time(t){}
    bool operator < (const pt &rsh)const{
        return time>rsh.time;
    }
};

char mp[maxn][maxn];
bool vis[maxn][maxn][6];
int n,m;

pt st,en;

int bfs(){
    priority_queue<pt> qu;
    qu.push(st);
    while(!qu.empty()){
        pt s = qu.top();qu.pop();
        if(vis[s.x][s.y][s.oxy]) continue;
        vis[s.x][s.y][s.oxy] = true;
        for(int i = 0; i<4; i++){
            int nx = s.x + dx[i];
            int ny = s.y + dy[i];
            if(nx<0||nx>=n||ny<0||ny>=m)continue;
            if(mp[nx][ny]=='T'){
                return s.time+1;
            }
            if(mp[nx][ny]=='P'){
                qu.push(pt(nx, ny, s.oxy, s.time));
            }
            else if(mp[nx][ny]=='#'){
                if(s.oxy>0)qu.push(pt(nx,ny,s.oxy-1,s.time+2));
            }
            else if(mp[nx][ny]=='B'){
                if(s.oxy<5){
                    qu.push(pt(nx, ny, s.oxy+1, s.time+1));
                }
                else  qu.push(pt(nx, ny, s.oxy, s.time+1));
            }
            else if(mp[nx][ny]=='.'||mp[nx][ny]=='S'){
                qu.push(pt(nx, ny, s.oxy, s.time+1));
            }
        }
    }
    return -1;
}

int main(){
    while(scanf("%d%d", &n, &m)!=EOF && n+m){
        memset(vis, false, sizeof(vis));
        for(int i = 0; i<n; i++){
            scanf("%s", mp[i]);
            for(int j = 0; j<m; j++){
                if(mp[i][j]=='S'){
                    st.x = i;st.y = j;st.oxy = 0;
                    st.time = 0;
                }
                if(mp[i][j] == 'T'){
                    en.x = i;en.y = j;en.oxy = 0;
                    en.time = 0;
                }
            }
        }
        printf("%d\n", bfs());
    }

}

 

### 关于‘哞叫时间II’问题的BFS解法 #### BFS算法概述 广度优先搜索(Breadth First Search, BFS)是一种用于图遍历或树遍历的经典算法。它按照层次顺序访问节点,通常借助队列实现。对于‘哞叫时间II’这一类涉及最短路径计算的问题,BFS非常适合解决基于无权图中的距离求解场景[^1]。 #### ‘哞叫时间II’问题描述 假设该问题是关于牛之间的通讯延迟优化问题,在给定的一组连接关系下,目标是最小化任意两头牛之间传递消息的最大时间。此问题可以建模为在一个加权图上找到某些特定条件下的最优路径长度问题[^2]。 #### 解决方案设计 以下是利用BFS来解决问题的核心思路: - **初始化阶段**: 创建一个二维数组或者邻接表表示农场中每一对奶牛间的连通性和权重;同时准备另一个辅助数据结构记录已到达各点所需的最小步数。 - **核心逻辑**: 使用标准BFS方法探索整个网络拓扑结构。每次从当前层扩展到下一可能未被触及的新位置,并更新相应的代价值直到完成全部结点处理为止。 下面给出一段伪代码展示如何通过Python实现上述过程: ```python from collections import deque def moo_call_time_ii_bfs(n, edges): graph = [[] for _ in range(n)] # 构造图 for u, v, w in edges: graph[u].append((v, w)) graph[v].append((u, w)) max_distance = 0 def bfs(start_node): distances = [-1]*n queue = deque() queue.append(start_node) distances[start_node] = 0 while queue: current = queue.popleft() for neighbor, weight in graph[current]: if distances[neighbor]==-1 or (distances[neighbor]>distances[current]+weight): distances[neighbor]=distances[current]+weight queue.append(neighbor) return max(distances) if all(d!=-1 for d in distances) else float('inf') result = min(bfs(i) for i in range(n)) return result if result !=float('inf') else -1 # Example Usage edges = [(0,1,5),(1,2,3)] # Sample edge list with weights. print(moo_call_time_ii_bfs(3, edges)) # Output should be the minimal maximum distance found via BFS traversal. ``` 以上程序片段展示了构建图模型以及执行多次BFS操作的过程,最终目的是找出能够使得最大通信延时尽可能低的最佳起点[^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值