Advertisement
Guest User

DFS

a guest
Sep 27th, 2016
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.92 KB | None | 0 0
  1. public static ArrayList<String> getWordLadderDFS(String start, String end) {
  2. ArrayList<String> wordLadder = new ArrayList<String>();
  3.  
  4. Set<String> dict = makeDictionary();
  5.  
  6. dict.remove(start); //remove the start word to say this node has been visited
  7.  
  8. ArrayList<String> branches = new ArrayList<String>(); //the arrayList containing all the branches of the current word
  9. for(String i: dict){ //iterate thru the dictionary and add all words that differ by one letter from the start
  10. if(oneLetterDiff(start, i))
  11. branches.add(i);
  12. }
  13.  
  14. if(branches.size() == 0) //if there are no next words, then there is no ladder
  15. return new ArrayList<String>();
  16.  
  17. if(branches.contains(end)){ //if the branch contains the last word already, return an array of size two
  18. ArrayList<String> ret = new ArrayList<String>();
  19. ret.add(start);
  20. ret.add(end);
  21. return ret;
  22. }
  23.  
  24.  
  25.  
  26. return wordLadder;
  27. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement