历届试题 青蛙跳杯子

题目链接:http://lx.lanqiao.cn/problem.page?gpid=T448

bfs题目,套模板即可详细可看bfs见解和模板

要点:

我们读题可以知道:空少青蛙多,如果我们遍历每只青蛙能否进洞,应该超时。

虽然我们应该遍历洞,看这个洞哪些青蛙可以进。

 

#include <iostream>
#include <cstdio>
#include <map>
#include <string>
#include <vector>
#include <algorithm>
#include <sstream>
#include <cstring>
#include <cmath>
#include <stack>
#include <queue>
#include <set>
#include <iomanip>
using namespace std;
int dir[6] = {-3, -2, -1, 1, 2, 3};
set<string> vis;
string beg, ed;
struct Node {
    string str;
    int dist;
    Node(string s, int d):
        str(s), dist(d) {}
};

void bfs() {
    queue<Node> queue;
    queue.push(Node(beg, 0));
    while(!queue.empty()) {
        Node u = queue.front(); queue.pop();
        string sstr = u.str; 
        int len = sstr.size();
        if(sstr == ed) {
            cout << u.dist << endl;
            return;
        }
        // 寻找每个空,看看哪些青蛙可以跳进这些空
        for(int i = 0; i < len; i++) {
            if(sstr[i] == '*') {
                for(int j = 0; j < 6; j++) {
                    // 这些位置的青蛙可以进
                    int p_t = i + dir[j];
                    string str_t = sstr;
                    if(p_t>=0 && p_t<len && sstr[p_t]!='*') {
                        // 跳进去 青蛙位置变为空*
                        str_t[i] = str_t[p_t];
                        str_t[p_t] = '*';
                        // 查重
                        if(!vis.count(str_t)) {
                            queue.push(Node(str_t, u.dist+1));
                            vis.insert(str_t);
                        }
                    }
                }
            }
        }

    } 
}

int main() {
    // freopen("i.txt", "r", stdin);
    // freopen("o.txt", "w", stdout);
    cin >> beg >> ed;
    bfs();
    return 0;
}


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值