[LeetCode]题解(python):127-Word Ladder

题目来源:

  https://leetcode.com/problems/word-ladder/


 

题意分析:

  和上一题目类似,给定一个beginWord和一个endWord,以及一个字典list。这题需要的是要beginWord转化成endWord的最短路径长度。


 

题目思路:

  最短路的思路。将beginWord放进队列,如果队列不为空,那么取出第一个数,将其周围的在字典的字符放进队列,直到周围的存在endword。


 

代码(python):

  

 1 import Queue
 2 class Solution(object):
 3     def ladderLength(self, beginWord, endWord, wordList):
 4         """
 5         :type beginWord: str
 6         :type endWord: str
 7         :type wordList: Set[str]
 8         :rtype: int
 9         """
10         q,ans = Queue.Queue(),{}
11         q.put(beginWord);wordList.add(endWord)
12         ans[beginWord] = 1
13         while not q.empty():
14             tmp = q.get()
15             if tmp == endWord:
16                 return ans[endWord]
17             for i in range(len(tmp)):
18                 part1,part2 = tmp[:i],tmp[i+1:]
19                 for j in 'abcdefghijklmnopqrstuvwxyz':
20                     if tmp[i] != j:
21                         newword = part1 + j + part2
22                         if newword in wordList:
23                             q.put(newword)
24                             ans[newword] = ans[tmp] + 1
25                             wordList.remove(newword)
26         return 0
27                         
View Code

 

posted @ 2016-03-22 15:26  Ry_Chen  阅读(1267)  评论(2编辑  收藏  举报