Skip to content

Instantly share code, notes, and snippets.

@blazs
Last active February 19, 2018 14:38
Show Gist options
  • Save blazs/f3250dfbd497d3f291fa803bd97664fc to your computer and use it in GitHub Desktop.
Save blazs/f3250dfbd497d3f291fa803bd97664fc to your computer and use it in GitHub Desktop.
Shortest path via BFS on implicit graph of words, induced by the dictionary of words, with an edge between each pair of words that differ by a single character.
import sys
import collections
import string
import logging
logging.basicConfig(level=logging.DEBUG)
LOGGER = logging.getLogger(__name__)
def shortest_path(beg, end, words, alphabet):
if beg == end:
return [beg]
seen = {w: False for w in words}
queue = [(beg, [beg])]
while queue:
w, l = queue.pop()
for idx in range(len(w) + 1):
for oth in alphabet:
new_s = w[:idx] + oth + w[idx+1:]
if new_s == end:
return l+[new_s]
elif new_s in seen and not seen[new_s]:
queue.insert(0, (new_s, l+[new_s]))
seen[new_s] = True
LOGGER.info("No path from '%s' to '%s' exists in this dictionary", beg, end)
return []
if __name__ == '__main__':
beg, end = sys.argv[1:]
alphabet = set(string.ascii_lowercase)
words = set()
with open('wordsEn.txt') as f:
words = set([w.strip() for w in f])
alphabet.add('') # so that we can remove characters
P = shortest_path(beg, end, words, alphabet)
print(' -> '.join(P))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment