Write a program to implement word ladder game. Where the single-letter substitution value is 1, and the single-letter deletion or addition of the value p>0 (P-value is specified by the consumer).
#include <iostream>#include <vector>#include <string>#include <fstream>#include <cmath>using namespace STD;Const intInfinty =99999;structvertex{ vector<int>Adj vector<int>WeightBOOLknown;intDiststringNameintpath;};voidPrintpath (intVindex, vector<Vertex>V) {if(vindex>=0&&v[vindex].path>-1) {Printpath (v[vindex].path,v);cout<<"to"; }cout<<v[vindex].name;}voidDijkstraintSindex,intTindex, vector<Vertex>& Vertices) {intSmallestdist;intSmallestvertex; Vertex v,s,t;intN=vertices.size (); vertices[sindex].dist=0; for(;;) {smallestdist= INFINITY; smallestvertex=-1; for(intI=0; i<n;i++) {if(! verties[i].known&&vertices[i].dist<smallestdist) {smallestdist=vertices[i].dist; smallestvertex=1; } }if(smallestvertex<0|| Smallestvertex==tindex) Break; vertices[smallestvertex].known=true; V=vertices[smallestvertex]; for(intj=0; J<v.adj.size (); j + +) {if(! (Vertices[v.adj[j].known)) {if(v.dist+v.weight[j]<vertices[v.adj[j].dist) {Vertices[v.adj[j]].dist=v.dist+v.weight ; Vertices[v.adj[j]].path=smallestvertex; }}}}}vertor<vertex> Readwords (IStream & in) {stringOneline; vector<Vertex>V Vertex W; while(In>>oneline) {w.name=oneline; w.known=false; w.path=-1; w.dist=infinity; V.push_back (w); }returnV;}intOnecharoff (Const string& Word1,Const string& Word2,intP) {stringBig,small,shrink;intCostif(ABS((int) (Word.length ()-word2.length ()) >1)return 0;Else if(Word1.length () ==word2.length ()) {intdiffs=0; for(intI=0; I<word1.length (); i++)if(Word1[i]!=word2[i])if(++diffs>1)return 0;if(diffs==1)return 1; }if(Word2.length () >word1.length ()) {big=word2; Small=word1; }Else{big=word1; Small=word2; } for(intI=0; I<big.length ()-1; i++) {Shrink=big.substr (0,1) +big.substr (i+1, Big,size ()-i-1);if(Shrink==small)returnP }if(Big.substr (0, Big.size ()-1) ==small)returnPElse return 0;}voidFilladjacencies ( vector<Vertex>& Words,intP) {intCost for(intI=0; I<words.size (); i++) { for(intj=i+1; J<words.size (); j + +) {Cost=onecharoff (words[i].name,words[j].name,p);if(cost>0) {Words[i].adj.push_back (j); Words[i].weight.push_back (cost); Words[j].adj.push_back (i); Words[j].weight.push_back (cost); } } }}intMain () {intP Ifstream Fin ("Dict.txt");stringW1,W2;intW1index,w2index;cout<<"What's the cost of a single char deletions:";Cin>>p; Vector<vertex> words=readwords (Fin); Do{cout<<"Enter Words in the dictionary:";Cin>>w1>>w2; for(w1index=0; W1index<words.size () &&words[w1index].name!=w1;w1index++)} while(W1index>=words.size () | | W2index>=words.size ()); Filladjacencies (WORDS,P); Dijkstra (w1index,w2index,words);cout<<endl; Printpath (w2index,words);return 0;}
To make this article get treatise and ask questions, reprint please indicate the source:
Http://blog.csdn.net/nomasp
Word Ladder Game