Skip to content

Instantly share code, notes, and snippets.

@wahyuoi
Created May 10, 2020 17:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wahyuoi/882a13508692e95f7069e5d15d4c8ca4 to your computer and use it in GitHub Desktop.
Save wahyuoi/882a13508692e95f7069e5d15d4c8ca4 to your computer and use it in GitHub Desktop.
Word Ladder
package WordLadder;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
class Solution {
public int ladderLength(String beginWord, String endWord, List<String> wordList) {
HashSet<String> c = new HashSet<>();
c.addAll(wordList);
int result = 0;
boolean found = false;
Set<String> visited = new HashSet<>();
List<String> queue = new ArrayList<>();
queue.add(beginWord);
visited.add(beginWord);
while (!found && !queue.isEmpty()) {
result++;
List<String> nextQueue = new ArrayList<>();
for (String s : queue) {
if (endWord.equals(s)) {
found = true;
break;
}
for (int i = 0; i < s.length(); i++) {
char[] chars = s.toCharArray();
for (char o = 'a'; o <= 'z'; o++) {
chars[i] = o;
String ns = new String(chars);
if (visited.contains(ns)) continue;
if (!c.contains(ns)) continue;
visited.add(ns);
nextQueue.add(ns);
}
}
}
queue = nextQueue;
}
return found ? result : 0;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment