Monday, November 23, 2015

Word-Ladder: How to find shortest transformation path from one word to another word in a given dictionary, changing one character at a time using java

import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;

class LadderWord{
String word;
int numStep;
LadderWord pre;

public LadderWord(String word,int numStep,LadderWord pre){
this.word=word;
this.numStep=numStep;
this.pre=pre;
}


}

public class WordLadderImpl{

public static void main(String [] arg){
Set s=new HashSet();
s.add("ait");
s.add("kit");
s.add("hot");
s.add("dot");
s.add("dog");
s.add("lot");
s.add("log");
s.add("hello");

findWordLadder("hit","cog",s);

}

public static void findWordLadder(String start, String dest, Set dic) {
LinkedList queue = new LinkedList(); // To do
// BFS
List unvisited = new ArrayList();
queue.add(new LadderWord(start, 1, null));
unvisited.addAll(dic);
unvisited.add(dest);

while (!queue.isEmpty()) {
LadderWord wordNode = queue.remove();
String word = wordNode.word;
int currentstep = wordNode.numStep;

if (word.equals(dest)) {
List list = new ArrayList();
while (wordNode != null) {
list.add(0, wordNode.word);
wordNode = wordNode.pre;

}
System.out.println("Shortes path length:" + currentstep
+ " path:" + list);
continue;
}

if (!unvisited.isEmpty()) {
char[] carr = word.toCharArray();
for (int i = 0; i < carr.length; i++) {
char tempc = carr[i];

for (char c = 'a'; c <= 'z'; c++) {
if (c != carr[i]) {
carr[i] = c;
}
String str = new String(carr);
if (unvisited.contains(str)) {
queue.add(new LadderWord(str, currentstep + 1,wordNode)); // adding into queue
if (!str.equals(dest)) { /*
* Since visited, removing
* from unvisited list
* except the destination
* word, because if it get
* removed it will only give
* only one path
*/
unvisited.remove(str);
}
}
}
carr[i] = tempc;
}

}

}

}



}

No comments:

Post a Comment