Skip to content

Instantly share code, notes, and snippets.

@priyankvex
Last active October 19, 2019 10:40
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 priyankvex/53059d596e30900b6e832f3e17739b0b to your computer and use it in GitHub Desktop.
Save priyankvex/53059d596e30900b6e832f3e17739b0b to your computer and use it in GitHub Desktop.
Shortest word ladder
class Solution(object):
def isAdjacent(self, first, second):
count = 0
for i, ch in enumerate(first):
if first[i] != second[i]:
count += 1
if count >= 2:
return False
return True
def solve(self, target, start, words):
q = [(start, 0)]
visited = {}
found = False
while q:
current_word, current_length = q[0]
for w in words:
if w not in visited and self.isAdjacent(current_word, w) and w != current_word:
q.append((w, current_length + 1))
visited[w] = current_word
if w == target:
found = True
break
if found:
break
q.pop(0)
if not found:
return []
current = target
path = [current]
while current in visited:
path.append(visited[current])
current = visited[current]
return list(reversed(path))
if __name__ == "__main__":
start = "DOG"
target = "CAT"
words = ["DOT", "DAT", "CAT", "POT", "PAT"]
ans = Solution().solve(target, start, words)
print(ans)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment