Advertisement
Guest User

Untitled

a guest
May 24th, 2015
211
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.52 KB | None | 0 0
  1. class Solution:
  2. # @param start, a string
  3. # @param end, a string
  4. # @param dict, a set of string
  5. # @return a list of lists of string
  6. def findLadders(self, start, end, dict):
  7. dict.add(start); dict.add(end)
  8. curLevel, nextLevel = set(), set()
  9. curLevel.add(start)
  10. prevWords, res = {}, []
  11.  
  12. while curLevel:
  13. for curWord in curLevel:
  14. dict.remove(curWord)
  15. for curWord in curLevel:
  16. for i in xrange(len(curWord)):
  17. left, right = curWord[:i], curWord[i + 1:]
  18. for offset in xrange(1, 26):
  19. mid = chr((ord(curWord[i]) - ord('a') + offset) % 26 + ord('a'))
  20. newWord = left + mid + right
  21. if newWord in dict:
  22. nextLevel.add(newWord)
  23. if newWord not in prevWords:
  24. prevWords[newWord] = set()
  25. prevWords[newWord].add(curWord)
  26. if end in prevWords:
  27. self.constructPathes(prevWords, start, end, [end], res)
  28. break
  29. curLevel = nextLevel
  30. nextLevel = set()
  31. return res
  32.  
  33. def constructPathes(self, prevWords, start, end, l, res):
  34. if end == start:
  35. res.append(l)
  36. return
  37.  
  38. s = prevWords[end]
  39. for word in s:
  40. self.constructPathes(prevWords, start, word, [word] + l, res)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement