1. class Pair
  2. {
  3. String word;
  4. int step;
  5.  
  6. Pair(String word, int step)
  7. {
  8. this.word = word;
  9. this.step = step;
  10. }
  11. }
  12.  
  13. class Solution {
  14.  
  15. public int ladderLength(String beginWord, String endWord, List<String> wordList) {
  16. // Step-1 Storing unique words from word list into set data structure
  17. HashSet<String> set = new HashSet<>();
  18. for(String word: wordList)
  19. set.add(word);
  20.  
  21. // Step-2 suppose endword itself is not present in wordlist then return NO PATH FOUND
  22. if(!set.contains(endWord))
  23. return 0;
  24.  
  25. // Step-2 Define a queue and store the <word, step>, we will start with beginWord with step taken as 1
  26. Queue<Pair> q = new LinkedList<>();
  27. q.add(new Pair(beginWord, 1));
  28.  
  29. // Step-4 Process the words stored in Queue
  30. while(!q.isEmpty())
  31. {
  32. Pair pair = q.poll();
  33. String word = pair.word;
  34. int step = pair.step;
  35.  
  36. // if we have reached the end word then return the steps taken to reach end word
  37. if(word.equals(endWord))
  38. return step;
  39.  
  40. // suppose word is "hit"
  41. // traversing through each character
  42. // and see if new word exists in set or not
  43. for(int i=0; i<word.length(); i++)
  44. {
  45. // we will try to change the letter from 'a' to 'z'
  46. for(char ch='a'; ch<='z';ch++)
  47. {
  48. char[] replacedCharArray = word.toCharArray();
  49. replacedCharArray[i] = ch;
  50. String newWord = new String(replacedCharArray);
  51.  
  52. // when newWord is present in set then add it to queue
  53. // and remove that from set
  54. if(set.contains(newWord))
  55. {
  56. // If we don’t remove a word after adding it to the queue, it could be visited again later through a different path.
  57. set.remove(newWord);
  58. q.add(new Pair(newWord, step+1));
  59. }
  60.  
  61. }
  62. }
  63. }
  64. return 0;
  65. }
  66. }
  67.  
  68.  
  69.  
  70. // bat, bag, sag, dag, dot
  71. // q: { (cat, 1) }
  72.  
  73. // c,a,t -> a,a,t -> b,a,t -> c,b,t... -> ca,a....
  74. // q: { (bat, 2) }
  75. // b,a,t -> a,a,t..-> b,b,t...-> ba,g
  76. // q: { (bag, 3) }
  77. // b,a,g -> a,a,g...s,a,g
  78. // q: { (sag, 4) }
  79. // s,a,g --> endWord return steps