双向bfs P1032 字串变换

这篇文章讨论了解决一个字符串变换问题的C++代码,利用BFS算法和哈希表来寻找从给定字符串A到字符串B的最短转换路径。作者提供了详细解释和代码片段,展示了如何在有限步骤内实现字符串的替换操作。

传送门icon-default.png?t=N7T8https://www.luogu.com.cn/problem/P1032

找一个最短方案,考虑用bfs(没试过单向,但是系数很大)

更详细的解答

下面是代码理解(注释版)

// Problem: 
//     P1032 [NOIP2002 提高组] 字串变换
//   
// Contest: Luogu
// URL: https://www.luogu.com.cn/problem/P1032
// Memory Limit: 125 MB
// Time Limit: 1000 ms
// 
// Powered by CP Editor (https://cpeditor.org)

#include<iostream>
#include<string>
#include<unordered_map>//哈希表 
#include<queue>
using namespace std;
string A,B;
string a[6],b[6];//方案
int len;

int extend(queue<string>&q,unordered_map<string,int> &ha,unordered_map<string,int> 
&hb,string a[],string b[]){
	int m=q.size();//每次只扩展一层
	while(m--){
		auto t=q.front();q.pop();
		for(int i=0;i<len;++i){//枚举方案
			for(unsigned int j=0;j<t.size();++j){//枚举起始位置
				if(t.substr(j,a[i].size())==a[i]){
					string ss=t.substr(0,j)+b[i]+t.substr(j+a[i].size());//字符串
					if(ha.count(ss)) continue;//如果这里之前有跳过
					if(hb.count(ss)) return ha[t]+hb[ss]+1;//对面之前有就返回答案
					ha[ss]=ha[t]+1;//更新
					q.push(ss); //入列
				}
			}
		}
	}
	return 11;
}

int bfs(){
	unordered_map<string,int> ha,hb;
	queue<string> qa,qb;
	qa.push(A);qb.push(B);
	ha[A]=0,hb[B]=0;//别忘,不然count找不到
	int t=10;
	while(t--){
		int ans;
		if(qa.size()<qb.size()) ans=extend(qa,ha,hb,a,b);
		else ans=extend(qb,hb,ha,b,a);//反着传,因为两边对应关系不同
		if(ans<=10) return ans;
	}
	return 11;
}

int main(){
    cin>>A>>B;
    while(cin>>a[len]){
    	cin>>b[len++];//len记录个数
    }
    if(bfs()<=10) cout<<bfs()<<endl;
    else cout<<"NO ANSWER!";
	return 0;
}

双向BFS(广度优先搜索)算法在字符串变换问题中具有广泛的应用,特别是在需要找到从一个字符串到另一个字符串的最短变换路径时。双向BFS通过从起点和终点同时展开搜索,逐步向中间靠拢,从而显著减少搜索空间,提高搜索效率。 在字符串变换问题中,通常的设定是给定一个起始字符串和一个目标字符串,以及一个字典集合,允许每次变换一个字符,并且每次变换后的字符串必须存在于字典中。目标是找到从起始字符串到目标字符串的最短变换序列。 ### 实现思路 1. **初始化两个队列**:分别从起始字符串和目标字符串出发,维护两个访问集合。 2. **交替扩展搜索**:每次选择当前队列中较小的一方进行扩展,以减少搜索空间。 3. **检查相遇条件**:如果在某一步骤中发现两个方向的搜索路径交汇,则说明找到了最短路径。 以下是一个使用双向BFS实现字符串变换的示例代码: ```python from collections import deque def ladderLength(beginWord, endWord, wordList): word_set = set(wordList) if endWord not in word_set: return 0 front_queue = deque([(beginWord, 1)]) back_queue = deque([(endWord, 1)]) front_visited = {beginWord: 1} back_visited = {endWord: 1} while front_queue and back_queue: # 从队列较短的一端扩展 if len(front_queue) <= len(back_queue): queue = front_queue visited = front_visited other_visited = back_visited else: queue = back_queue visited = back_visited other_visited = front_visited for _ in range(len(queue)): current_word, level = queue.popleft() for i in range(len(current_word)): for c in 'abcdefghijklmnopqrstuvwxyz': next_word = current_word[:i] + c + current_word[i+1:] if next_word in word_set and next_word not in visited: if next_word in other_visited: return level + other_visited[next_word] visited[next_word] = level + 1 queue.append((next_word, level + 1)) return 0 ``` ### 示例说明 - **初始化**:将起始词和目标词分别放入两个队列中,并记录它们的访问状态。 - **扩展搜索**:每次选择当前队列中较短的队列进行扩展,生成所有可能的变换词。 - **路径交汇**:当某个变换词已经出现在另一个方向的访问集合中时,说明找到了最短路径。 双向BFS的关键在于通过从两端同时搜索,减少不必要的路径扩展,从而提高搜索效率[^1]。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值