Skip to content

Instantly share code, notes, and snippets.

@charlespunk
Last active December 20, 2015 23:59
Show Gist options
  • Save charlespunk/6216934 to your computer and use it in GitHub Desktop.
Save charlespunk/6216934 to your computer and use it in GitHub Desktop.
Given two words (start and end), and a dictionary, find the length of shortest transformation sequence from start to end, such that:
Only one letter can be changed at a time
Each intermediate word must exist in the dictionary
For example,
Given:
start = "hit"
end = "cog"
dict = ["hot","dot","dog","lot","log"]
As one shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -> "cog",
return its length 5.
Note:
Return 0 if there is no such transformation sequence.
All words have the same length.
All words contain only lowercase alphabetic characters.
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Queue;
public class Solution {
public int ladderLength(String start, String end, HashSet<String> dict) {
// Start typing your Java solution below
// DO NOT write main() function
if(start.equals(end)) return 0;
HashSet<String> hasVisited = new HashSet<String>();
Queue<Path> q = new LinkedList<Path>();
Path begin = new Path(start, 1);
q.offer(begin);
hasVisited.add(start);
while(!q.isEmpty()){
Path path = q.poll();
char[] chars = path.word.toCharArray();
for(int i = 0; i < chars.length; i++){
for(int j = 97; j <= 122; j++){
char odd = chars[i];
if(chars[i] != (char) j){
chars[i] = (char) j;
String newWord = String.valueOf(chars);
if(newWord.equals(end)) return path.level + 1;
if(dict.contains(newWord) && !hasVisited.contains(newWord)){
q.offer(new Path(newWord, path.level + 1));
hasVisited.add(newWord);
}
}
chars[i] = odd;
}
}
}
return 0;
}
class Path{
String word;
int level;
Path(String word, int level){
this.word = word;
this.level = level;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment