Advertisement
Guest User

Untitled

a guest
Jul 23rd, 2018
289
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.99 KB | None | 0 0
  1. class Solution(object):
  2. def ladderLength(self, beginWord, endWord, wordList):
  3. """
  4. :type beginWord: str
  5. :type endWord: str
  6. :type wordList: List[str]
  7. :rtype: int
  8. """
  9. if endWord not in wordList:
  10. return 0
  11. queue = []
  12. queue.append((beginWord, 1))
  13. visited = set()
  14. while len(queue)>0:
  15. currword, currlvl = queue.pop(0)
  16. if currword == endWord:
  17. return currlvl
  18. for word in wordList:
  19. if word not in visited:
  20. if self.checkifonediff(currword, word):
  21. visited.add(word)
  22. queue.append((word, currlvl + 1))
  23. return 0
  24.  
  25. def checkifonediff(self, cword, word):
  26. count = 0
  27. for i in range(len(cword)):
  28. if cword[i] != word[i]:
  29. count += 1
  30. if count != 1:
  31. return False
  32. return True
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement