Skip to content

Commit d53070c

Browse files
Accepted
1 parent 2418492 commit d53070c

File tree

1 file changed

+121
-0
lines changed

1 file changed

+121
-0
lines changed

problems/src/WordLadderII.java

Lines changed: 121 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,121 @@
1+
import java.util.*;
2+
3+
/**
4+
* Created by gouthamvidyapradhan on 24/03/2017.
5+
*/
6+
public class WordLadderII
7+
{
8+
9+
private static Queue<String> queue = new ArrayDeque<>();
10+
private static Set<String> dictionary = new HashSet<>();
11+
private static final String CONST = "abcdefghijklmnopqrstuvwxyz";
12+
private static Map<String, Set<String>> graph = new HashMap<>();
13+
private static Map<String, Integer> minDistance = new HashMap<>();
14+
private static List<List<String>> result = new ArrayList<>();
15+
16+
17+
18+
/**
19+
* Main method
20+
* @param args
21+
* @throws Exception
22+
*/
23+
public static void main(String[] args) throws Exception
24+
{
25+
List<String> dic = Arrays.asList("kid","tag","pup","ail","tun","woo","erg","luz","brr","gay","sip","kay","per","val","mes","ohs","now","boa","cet","pal","bar","die","war","hay","eco","pub","lob","rue","fry","lit","rex","jan","cot","bid","ali","pay","col","gum","ger","row","won","dan","rum","fad","tut","sag","yip","sui","ark","has","zip","fez","own","ump","dis","ads","max","jaw","out","btu","ana","gap","cry","led","abe","box","ore","pig","fie","toy","fat","cal","lie","noh","sew","ono","tam","flu","mgm","ply","awe","pry","tit","tie","yet","too","tax","jim","san","pan","map","ski","ova","wed","non","wac","nut","why","bye","lye","oct","old","fin","feb","chi","sap","owl","log","tod","dot","bow","fob","for","joe","ivy","fan","age","fax","hip","jib","mel","hus","sob","ifs","tab","ara","dab","jag","jar","arm","lot","tom","sax","tex","yum","pei","wen","wry","ire","irk","far","mew","wit","doe","gas","rte","ian","pot","ask","wag","hag","amy","nag","ron","soy","gin","don","tug","fay","vic","boo","nam","ave","buy","sop","but","orb","fen","paw","his","sub","bob","yea","oft","inn","rod","yam","pew","web","hod","hun","gyp","wei","wis","rob","gad","pie","mon","dog","bib","rub","ere","dig","era","cat","fox","bee","mod","day","apr","vie","nev","jam","pam","new","aye","ani","and","ibm","yap","can","pyx","tar","kin","fog","hum","pip","cup","dye","lyx","jog","nun","par","wan","fey","bus","oak","bad","ats","set","qom","vat","eat","pus","rev","axe","ion","six","ila","lao","mom","mas","pro","few","opt","poe","art","ash","oar","cap","lop","may","shy","rid","bat","sum","rim","fee","bmw","sky","maj","hue","thy","ava","rap","den","fla","auk","cox","ibo","hey","saw","vim","sec","ltd","you","its","tat","dew","eva","tog","ram","let","see","zit","maw","nix","ate","gig","rep","owe","ind","hog","eve","sam","zoo","any","dow","cod","bed","vet","ham","sis","hex","via","fir","nod","mao","aug","mum","hoe","bah","hal","keg","hew","zed","tow","gog","ass","dem","who","bet","gos","son","ear","spy","kit","boy","due","sen","oaf","mix","hep","fur","ada","bin","nil","mia","ewe","hit","fix","sad","rib","eye","hop","haw","wax","mid","tad","ken","wad","rye","pap","bog","gut","ito","woe","our","ado","sin","mad","ray","hon","roy","dip","hen","iva","lug","asp","hui","yak","bay","poi","yep","bun","try","lad","elm","nat","wyo","gym","dug","toe","dee","wig","sly","rip","geo","cog","pas","zen","odd","nan","lay","pod","fit","hem","joy","bum","rio","yon","dec","leg","put","sue","dim","pet","yaw","nub","bit","bur","sid","sun","oil","red","doc","moe","caw","eel","dix","cub","end","gem","off","yew","hug","pop","tub","sgt","lid","pun","ton","sol","din","yup","jab","pea","bug","gag","mil","jig","hub","low","did","tin","get","gte","sox","lei","mig","fig","lon","use","ban","flo","nov","jut","bag","mir","sty","lap","two","ins","con","ant","net","tux","ode","stu","mug","cad","nap","gun","fop","tot","sow","sal","sic","ted","wot","del","imp","cob","way","ann","tan","mci","job","wet","ism","err","him","all","pad","hah","hie","aim","ike","jed","ego","mac","baa","min","com","ill","was","cab","ago","ina","big","ilk","gal","tap","duh","ola","ran","lab","top","gob","hot","ora","tia","kip","han","met","hut","she","sac","fed","goo","tee","ell","not","act","gil","rut","ala","ape","rig","cid","god","duo","lin","aid","gel","awl","lag","elf","liz","ref","aha","fib","oho","tho","her","nor","ace","adz","fun","ned","coo","win","tao","coy","van","man","pit","guy","foe","hid","mai","sup","jay","hob","mow","jot","are","pol","arc","lax","aft","alb","len","air","pug","pox","vow","got","meg","zoe","amp","ale","bud","gee","pin","dun","pat","ten","mob");
26+
new WordLadderII().findLadders("cet", "ism", dic);
27+
}
28+
29+
public List<List<String>> findLadders(String beginWord, String endWord, List<String> wordList)
30+
{
31+
dictionary.addAll(wordList);
32+
bfs(beginWord, endWord, wordList);
33+
List<String> path = new ArrayList<>();
34+
path.add(beginWord);
35+
dfs(beginWord, endWord, path);
36+
System.out.println(result);
37+
return result;
38+
}
39+
40+
/**
41+
* Bfs
42+
* @param beginWord begin word
43+
* @param endWord end word
44+
* @param wordList wordlist
45+
*/
46+
private void bfs(String beginWord, String endWord, List<String> wordList)
47+
{
48+
queue.offer(beginWord);
49+
minDistance.put(beginWord, 0);
50+
while(!queue.isEmpty())
51+
{
52+
String currWord = queue.poll();
53+
StringBuilder childSb = new StringBuilder(currWord);
54+
for(int j = 0, ln = childSb.length(); j < ln; j ++ )
55+
{
56+
for(int i = 0, l = CONST.length(); i < l; i ++ )
57+
{
58+
char old = childSb.charAt(j);
59+
childSb.replace(j, j + 1, String.valueOf(CONST.charAt(i)));
60+
String child = childSb.toString();
61+
if(dictionary.contains(child))
62+
{
63+
if(minDistance.get(child) == null)
64+
{
65+
minDistance.put(child, minDistance.get(currWord) + 1);
66+
addChild(currWord, child);
67+
if(!child.equals(endWord))
68+
queue.offer(child);
69+
}
70+
else
71+
{
72+
if(minDistance.get(child) == (minDistance.get(currWord) + 1))
73+
addChild(currWord, child);
74+
}
75+
}
76+
childSb.replace(j, j + 1, String.valueOf(old));
77+
}
78+
}
79+
}
80+
}
81+
/**
82+
* Add child
83+
* @param parent parent
84+
* @param child child
85+
*/
86+
private void addChild(String parent, String child)
87+
{
88+
Set<String> children = graph.get(parent);
89+
if(children == null)
90+
children = new HashSet<>();
91+
children.add(child);
92+
graph.put(parent, children);
93+
}
94+
95+
/**
96+
* Dfs to build path
97+
* @param currWord node
98+
* @param endWord endword
99+
* @param path path
100+
*/
101+
private void dfs(String currWord, String endWord, List<String> path)
102+
{
103+
if(currWord.equals(endWord))
104+
{
105+
result.add(new ArrayList<>(path));
106+
}
107+
else
108+
{
109+
Set<String> children = graph.get(currWord);
110+
if(children != null)
111+
{
112+
for(String c : children)
113+
{
114+
path.add(c);
115+
dfs(c, endWord, path);
116+
path.remove(path.size() - 1);
117+
}
118+
}
119+
}
120+
}
121+
}

0 commit comments

Comments
 (0)