Skip to content

Instantly share code, notes, and snippets.

@vgrichina
Created December 8, 2014 16:37
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 vgrichina/7906906546b2bf2a65d3 to your computer and use it in GitHub Desktop.
Save vgrichina/7906906546b2bf2a65d3 to your computer and use it in GitHub Desktop.
import string
class Solution:
# @param start, a string
# @param end, a string
# @param dict, a set of string
# @return an integer
def ladderLength(self, start, end, dict):
dict += [end]
def next_edges(word):
edges = []
word_chars = list(word)
for i in range(len(word)):
new_word_chars = list(word_chars)
for c in string.lowercase:
new_word_chars[i] = c
new_word = "".join(new_word_chars)
if new_word in dict and new_word not in edges:
edges += [new_word]
return edges
visited = set()
queue = set([start])
d = 1
while len(queue) > 0:
#print queue
new_queue = set()
for cur in queue:
if cur == end:
return d
visited.add(cur)
new_queue |= {e for e in next_edges(cur) if e not in visited}
queue = new_queue
d += 1
return 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment