P1825 [USACO11OPEN] Corn Maze S

带传送门的bfs。

传送门是双向的,且每个是只有一对,用字符A - Z表示。

题目保证了一定有解,不会出现在两个传送门之间来回跳的情况。

简单bfs代码如下:

void solve() {
    int n,m; cin>>n>>m;
    vector<string> ph(n);
    for(auto &t: ph) cin>>t;
    vector<vector<int>> vis(n, vector<int>(m));
    
    // x, y, cnt  横纵坐标 从起点到(x,y)的用时
    queue<array<int,3>> q; // x, y, cnt;

    // 存入每一对传送门的两个位置信息
    map<char, vector<array<int,2>>> mp;
    for(int i = 0; i < n; ++i) {
        for(int j = 0; j < m; ++j) {
            if(ph[i][j] == '@') {
                // 将起点push到队列
                q.push({i,j, 0});
                vis[i][j] = 1;
                // break;
            }
            // 将传送门存入
            if(ph[i][j] != '@' && ph[i][j] != '=' && ph[i][j] != '#' && ph[i][j] != '.') {
                mp[ph[i][j]].push_back({i,j});
            }
        }
    }
    while(q.size()) {
        auto tmp = q.front(); q.pop();
        int x = tmp[0], y = tmp[1], ct = tmp[2];
        for(int i = 0;i < 4; ++i) {
            int xx = x + fx[i], yy = y + fy[i];
            if(xx < 0 || xx >= n || yy < 0 || yy >= m) continue;
            if(ph[xx][yy] == '#' || vis[xx][yy]) continue;
            if(ph[xx][yy] == '=') {
                cout<<ct+1<<endl;
                return ;
            }
            if(ph[xx][yy] == '.') {
                vis[xx][yy] = 1;
                q.push({xx, yy, ct + 1});
            } else {
                // 如果是传送门,则要进行传送
                auto va = mp[ph[xx][yy]];
                for(auto &t: va) {
                    int sx = t[0], sy = t[1];
                    if(sx == xx && sy == yy) continue;
                    q.push({sx,sy,ct+1});
                }
            }
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

golemon.

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值