Word Ladder

Word Ladder

题目描述

Given two words (beginWord and endWord), and a dictionary’s word list, find the length of shortest transformation sequence from beginWord to endWord, such that:

Only one letter can be changed at a time.
Each transformed word must exist in the word list. Note that beginWord is not a transformed word.
Note:

Return 0 if there is no such transformation sequence.
All words have the same length.
All words contain only lowercase alphabetic characters.
You may assume no duplicates in the word list.
You may assume beginWord and endWord are non-empty and are not the same.
You may assume endWord is a transformed word.
输入
第一行,字符串beginWord。 第二行,字符串endWord。 第三行,word list中的word个数N(1=<N<=50)。 后面N行为N个word list中的word。 (beginWord, endWord和word list中word的长度l的范围为3<=l<=5)

输出
shortest transformation sequence 的长度,如果不存在则输出0。

Example
Input:

hit

cog

6

hot

dot

dog

lot

log

cog

Output:

5

Explanation:

As one shortest transformation is “hit” -> “hot” -> “dot” -> “dog” -> “cog”, return its length 5.

题意

有一个开始字符串start,和一个结束字符串end,和一组转字符串wordlist,要将start替换成end,要求每次只能替换一个字符,并且替换后的字符串是wordlist中的,输出替换序列的最短长度,如果不能成功替换,则输出0

思路

  • 广度优先搜索,从开始节点出发,遍历所有没有访问过的数,(需要一个数组来保存是否访问过这一属性 visited[])

  • 找到所有相邻节点(需要一个判断函数,看是否相邻可以完成交换操作 canpush(),用一个队列q来保存循环中得到所有相邻的节点)

  • 再依次对相邻节点做相同操作()(处理的是q.front(),记得将该节点pop,为了得到结果,还需要保存这个节点在交换序列中的位序,使用pair,和节点的下标一起保存在队列q中),直到在遍历的过程中得到end

参考:
https://www.jianshu.com/p/753bd585d57e

代码

#include<iostream>
#include<vector>
#include<queue>
#include<string> 
using namespace std; 

bool canpush(const string &a,const string &b)  //开始忘记写&
{
	int n=a.length();  
	int num=0;
	for(int i=0;i<n;i++){
		if(a[i]!=b[i]){
			num++;
		}
	}
	return num==1;
} 

int transform(string start,string end,vector<string> &dict)
{
	queue<pair<int,int> > q;//> >中间要有空格 ,不太了解pair 的相关操作 
	int len=dict.size();
	bool visited[len];
	for(int i=0;i<len;i++){
		visited[i]=false;
	}
	q.push(make_pair(-1,1));
	int f,t;
	string front;  //忘记声明front 
	while(!q.empty())
	{
		f=q.front().first;
		t=q.front().second;
		q.pop(); 
		if(f==-1){
			front=start;
		}
		else{
			front=dict[f];
		}
		if(front==end)
		{
			return t;
		}
		for(int i=0;i<len;i++){ //len写成了n 
			if(!visited[i] && canpush(front,dict[i])){
				q.push(make_pair(i,t+1));
				visited[i]=true;
			}
		}
	}
	return 0; //把所有的都弹出来的但是没找到 front==end,也就是无法通过交换得到 
}

int main()
{
	string start,end;
	cin>>start>>end;
	int n;
	cin>>n;
	vector<string> dict;
	string temp;
	for(int i=0;i<n;i++){
		cin>>temp;
		dict.push_back(temp); 
		
	}
	cout<<transform(start,end,dict)<<endl;
	
	return 0;
} 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值