Created
April 16, 2015 06:29
-
-
Save littleq0903/9a5c6472c35fa4f3ae3a to your computer and use it in GitHub Desktop.
Solution to https://leetcode.com/problems/word-ladder/
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
class Solution: | |
# @param beginWord, a string | |
# @param endWord, a string | |
# @param wordDict, a set<string> | |
# @return an integer | |
def is_intermediate(self, a, b): | |
return len(filter(lambda x: x, [a[i] != b[i] for i in range(len(a))])) == 1 | |
def dfs(self, themap, start, end, limit): | |
if limit <= 0: | |
return 0 | |
if start == end: | |
return 1 | |
else: | |
inter = [self.dfs(themap, e, end, limit-1) for e in themap[start]] | |
if inter: | |
return 1 + min(inter) | |
else: | |
return 0 | |
def ladderLength(self, beginWord, endWord, wordDict): | |
themap = {} | |
wordDict = set(list(wordDict) + [beginWord, endWord]) | |
for s in wordDict: | |
themap[s] = [] | |
for start in wordDict: | |
for end in wordDict: | |
if self.is_intermediate(start, end): | |
themap[start].append(end) | |
return self.dfs(themap, beginWord, endWord, len(beginWord)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment