Created
May 10, 2020 17:15
-
-
Save wahyuoi/882a13508692e95f7069e5d15d4c8ca4 to your computer and use it in GitHub Desktop.
Word Ladder
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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