POJ4128 单词序列(BFS)

Description:

给出两个单词(开始单词和结束单词)以及一个词典。找出从开始单词转换到结束单词,所需要的最短转换序列。转换的规则如下:
1、每次只能改变一个字母
2、转换过程中出现的单词(除开始单词和结束单词)必须存在于词典中
例如:
开始单词为:hit
结束单词为:cog
词典为:[hot,dot,dog,lot,log,mot]
那么一种可能的最短变换是: hit -> hot -> dot -> dog -> cog,
所以返回的结果是序列的长度5;
注意:
1、如果不能找到这种变换,则输出0;
2、词典中所有单词长度一样;
3、所有的单词都由小写字母构成;
4、开始单词和结束单词可以不在词典中。

解题思路:

算法标签:BFS
对每个与上一个字符串是否有一个字符不相同且未被访问过就入队,最先找到结束单词就是最短序列。
注意要用 vis 数组保存是否已经入队,否则会做重复的搜索而且会超内存,注意 vis 的初始化(记得定义全局变量不是初始化false,但是我的wrong了)

代码:

// TSWorld
#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <queue>
#include <vector>
using namespace std;

#define rep(i,l,r) for(int i = l; i <= r;i++)
#define ll long long

const int N = 40;
string start,en;
string dic[N];
int times;

struct Node {
	string word;
	int step;
};

queue<Node>q;
bool vis[N];

bool issamed(string src,string des) {
	int same = 0;
	for(int i = 0;i < src.length();i++) {
		if(src[i] != des[i])
			same++;
		if(same > 1)
			break;
	}
	if(same == 1){
		//cout<<src<<" "<<des<<endl;
		return true;
	}
	else 
		return false;
}
void Bfs() {

	struct Node head;
	struct Node temp;
	bool isresult = false;
	memset(vis,false,sizeof(vis));
	
	while(!q.empty()) {
		
		head = q.front();
		q.pop();

		if(head.word == en){
			isresult = true;
			break;
		}

		for(int i = 1;i <= times;i++) {
			if(issamed(head.word,dic[i]) && !vis[i]) {
				temp.word = dic[i];
				temp.step = head.step+1;
				vis[i] = true;
				q.push(temp);
			}
		}
	}
	if(isresult)
		cout<<head.step;
	else
		cout<<0;
}
int main()
{
	struct Node head;
	cin>>start>>en;
	times = 1;
	while(cin>>dic[times]){
		times++;
	}

	dic[times] = en;
	head.word = start;
	head.step = 1;
	q.push(head);

	Bfs();
	return 0;
}
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值