Word Ladder
来源:互联网 发布:yy协议软件下载 编辑:程序博客网 时间:2024/06/05 18:24
词梯:相同长度的两个单词,从源词每次更换一个字母,最终得到目标单词.
将词典单词读入到集合s中.利用源单词合成Node类型,放入队列q中,并从s中删除.每次从队头取出一个单词,并从s中搜索所有的可能相邻单词(其中只有一个字母不同的单词)
满足则放入队尾并从s中删除.直到队头单词为目标单词或队列为空退出循环.
#include <iostream>#include <string>#include <queue>#include <vector>#include <stack>#include <set>#include <stdlib.h>using namespace std;struct Node{ string str; queue<string> strqueue; Node():str(""){} Node(string st):str(st){}};void smallToCapital(string& a){int len=a.size();for(int i=0;i<len;i++)if(a[i]>='a'&&a[i]<='z')a[i]=a[i]-('a'-'A');}void capitalToSmall(string& a){int len=a.size();for(int i=0;i<len;i++)if(a[i]>='A'&&a[i]<='Z')a[i]=a[i]+('a'-'A');}int main(){ string c,d; cin>>c>>d; if(c.length()!=d.length()){ cout<<"Length not same"<<endl; system("pause"); return -1;} smallToCapital(c); smallToCapital(d); Node* a=new Node(c); a->strqueue.push(c); Node* b=new Node(d); b->strqueue.push(d); set<string> s; string t; freopen("D:\\in.txt","r",stdin); //字典文件 while(cin>>t){ s.insert(t); }<span style="white-space:pre"></span>if(s.find(c)==s.end()||s.find(d)==s.end()){if(s.find(c)==s.end()) cout<<"Source word unavailable"<<endl;if(s.find(d)==s.end()) cout<<"Target word unavailable"<<endl;return -1;} queue<Node*> q; q.push(a); s.erase(c); while(!q.empty()){ if(q.front()->str==b->str){ cout<<q.front()->str<<" "<<q.size()<<endl; cout<<"Found"<<endl;cout<<q.front()->strqueue.size()<<endl; while((q.front()->strqueue).size()!=0){ // Output all the related strings. capitalToSmall(q.front()->strqueue.front());cout<<q.front()->strqueue.front()<<" "; q.front()->strqueue.pop(); } break; } string tmp=q.front()->str; int len=(q.front()->str).length(); for(int i=0;i<len;i++) for(char c='A';c<='Z';c++) if(c!=q.front()->str[i]){ tmp=q.front()->str; tmp[i]=c; set<string>::iterator it=s.find(tmp); if(it!=s.end()){ Node* k=new Node(tmp); k->strqueue=q.front()->strqueue; k->strqueue.push(k->str); q.push(k); s.erase(*it);}} cout<<q.front()->str<<" "<<q.size()<<" "<<endl; q.pop(); } if(q.empty()) cout<<"Not found"<<endl; system("pause");
0 0
- Word Ladder
- Word Ladder
- word ladder
- Word Ladder
- Word Ladder
- Word Ladder
- Word Ladder
- Word Ladder
- Word Ladder
- Word Ladder
- Word Ladder
- Word Ladder
- Word Ladder
- Word Ladder
- Word Ladder
- Word Ladder
- Word Ladder
- Word Ladder
- SIP相关的RFC文档全收集
- JSP内置对象(3)-----session对象
- 树的概念总结;树的存储结构;树、二叉树、森林的相互转换
- AndroidStudio打包报错:duplicate entry
- javax.validation.ValidationException: HV000183: Unable to load 'javax.el.ExpressionFactory'. Check t
- Word Ladder
- 数据结构之时间复杂度和空间复杂度
- Linux进程间通信的几种方式总结
- N阶幻方
- 笔试题88.腾讯2017暑期实习生笔试题(有趣数字)
- HTML表格标签
- c3p0,druid,dbcp的性能比较
- 909422229__XML的实体引用
- nyoj 1112求次数 STL