Created
March 17, 2020 20:06
-
-
Save junminstorage/d97cc4744c5bf7155774fe230897bc2c to your computer and use it in GitHub Desktop.
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
public List<List<String>> findLadders(String start, String end, List<String> wordList) { | |
Set<String> dict = new HashSet<>(); | |
for(String w : wordList) | |
dict.add(w); | |
int len = start.length(); | |
Set<String> visited = new HashSet<>(); | |
Set<String> queue = new HashSet<>(); | |
queue.add(start); | |
visited.add(start); | |
Map<String, Set<String>> parents = new HashMap<>(); | |
boolean found = false; | |
while(!queue.isEmpty()) { | |
Set<String> nextLevel = new HashSet<>(); | |
for(String current : queue) { | |
if(current.equals(end)) { | |
found = true; | |
break; | |
} | |
char[] chars = current.toCharArray(); | |
for(int i = 0; i<len; i++){ | |
char original = chars[i]; | |
for(int c='a'; c<='z'; c++) { | |
chars[i] = (char)c; | |
String s = String.valueOf(chars); | |
if(!visited.contains(s) && dict.contains(s)) { | |
nextLevel.add(s); | |
visited.add(s); | |
} | |
if(nextLevel.contains(s) && dict.contains(s)){ | |
if(!parents.containsKey(s)) | |
parents.put(s, new HashSet<>()); | |
parents.get(s).add(current); | |
} | |
chars[i] = original; | |
} | |
} | |
} | |
queue = nextLevel; | |
} | |
if(found) { | |
//dfs parents | |
return dfs(end, start, parents); | |
}else{ | |
return new ArrayList<>(); | |
} | |
} | |
private List<List<String>> dfs(String current, String end, Map<String, Set<String>> parents) { | |
if(current.equals(end)) { | |
List<List<String>> list = new ArrayList<>(); | |
List<String> item = new ArrayList<>(); | |
item.add(current); | |
list.add(item); | |
return list; | |
} | |
List<List<String>> list = new ArrayList<>(); | |
for(String p : parents.get(current)) { | |
for(List<String> item : dfs(p, end, parents)) { | |
item.add(current); | |
list.add(item); | |
} | |
} | |
return list; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment