bfs | 洛谷 | P1032

本文详细探讨了洛谷P1032问题的解决方案,重点讲解了使用宽度优先搜索(BFS)算法时需要注意的要点,包括确保在判断结束条件时已到达目标状态,以避免循环导致的误判。

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

https://www.luogu.org/problemnew/show/P1032

  • bfs要注意确认是否进入过终态, 防止while语句在没有进入终态的情况下结束并进行判别.
#include <bits/stdc++.h>
#define FF(a,b) for(int a=0;a<b;a++)
#define F(a,b) for(int a=1;a<=b;a++)
#define LEN 40
#define bug(x) cout<<#x<<"="<<x<<endl;

using namespace std;

int N=0;//转换模式的数目
string orig[LEN],dest[LEN];
map<string,bool> vis;
string S,E;

//多值替换. 对于原串str, 如果有多个子串匹配model的from串,将所有的替换结果保存在ans中.
bool translate(string& str,int model,vector<string>& ans){
    string from=orig[model];
    string to=dest[model];
    int pos,pre=0;
    bool isFind=false;
    while(   ( pos=str.find(from,pre)  )!=string::npos  ){
        isFind=true;
        string tmp=str;
        tmp.replace(pos,from.size(),to);
        ans.push_back(tmp);
        pre=pos+from.size();
    }
    return isFind;
}

void bfs(){
    queue<string> q;
    q.push(S);
    vis[S]=1;
    int step=0;
    bool isFind=false;
    while(!q.empty()){
        int sz=q.size();
        while(sz--){
            string u=q.front();
            q.pop();
            if(u==E){
                isFind=true;
                goto END;
            }
            FF(i,N){    //对于N种情况进行分析
                vector<string> v;
                if(translate(u,i,v)){
                    FF(j,v.size()){
                        string nd=v[j];
                        if(!vis[nd]){
                            vis[nd]=1;
                            q.push(nd);
                        }
                    }
                }
            }
        }
        step++;
    }
    END:
    if (step > 10 || step == 0 || !isFind)	//特别注意isFind.如果while语句自然死亡,就要确定是否进入了终态
        cout << "NO ANSWER!" << endl;
    else
        cout << step<< endl;
}

int main()
{
    freopen("./in2","r",stdin);
    cin>>S>>E;
    while(cin>>orig[N]>>dest[N])
        N++;
    bfs();
    return 0;
}



### 关于洛谷 P1032 使用双向BFS算法的解题思路 #### 问题背景与挑战 对于洛谷平台上的P1032题目,虽然官方提示该题可能存在一定的局限性和测试数据较弱的情况[^1],但是采用双向广度优先搜索(Bidirectional BFS)仍然是一种有效的策略来优化求解路径问题。 #### 双向BFS的核心概念 双向BFS是从起始节点和目标节点分别启动两个独立的广度优先遍历过程。每次迭代时交替扩展这两个方向上的边界层直到两者相遇为止。这种方法能够显著减少所需探索的状态空间大小,在理论上可将时间复杂度降低一半以上。 #### 实现要点分析 - **初始化队列**:创建两个队列`startQueue`用于存储从起点出发可达的所有位置;以及`endQueue`保存由终点反向追溯所能到达的位置集合。 - **记录访问标记**:设立两套布尔数组`visitedStart[]` 和 `visitedEnd[]`, 分别用来跟踪已处理过的结点以防重复计算。 - **终止条件判断**:当任意一次扩张操作使得当前层次内的某个顶点既存在于正向也存在于逆向已经访问列表之中,则说明找到了一条连接源汇两点的有效通路并立即停止进一步深入探寻其他可能性分支。 ```cpp #include <iostream> #include <queue> using namespace std; struct State { string s; int step; }; bool bfs(queue<State>& q, unordered_map<string,int>& visited,unordered_map<string,int> &otherVisited){ while(!q.empty()){ auto cur=q.front();q.pop(); // Check if current state is found in the opposite direction's map. if(otherVisited.count(cur.s)) return true; // Process neighbors and add them to queue... } } } ``` 上述伪代码片段展示了如何利用C++标准库中的容器类实现基本框架结构的一部分逻辑控制流程。需要注意的是实际编码过程中还需要考虑具体应用场景下的细节差异调整相应部分功能模块设计以适应特定需求场景的要求。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值