题目来源:
https://leetcode.com/problems/word-ladder/
题意分析:
和上一题目类似,给定一个beginWord和一个endWord,以及一个字典list。这题需要的是要beginWord转化成endWord的最短路径长度。
题目思路:
最短路的思路。将beginWord放进队列,如果队列不为空,那么取出第一个数,将其周围的在字典的字符放进队列,直到周围的存在endword。
代码(python):
import Queue
class Solution(object):
def ladderLength(self, beginWord, endWord, wordList):
"""
:type beginWord: str
:type endWord: str
:type wordList: Set[str]
:rtype: int
"""
q,ans = Queue.Queue(),{}
q.put(beginWord);wordList.add(endWord)
ans[beginWord] = 1
while not q.empty():
tmp = q.get()
if tmp == endWord:
return ans[endWord]
for i in range(len(tmp)):
part1,part2 = tmp[:i],tmp[i+1:]
for j in 'abcdefghijklmnopqrstuvwxyz':
if tmp[i] != j:
newword = part1 + j + part2
if newword in wordList:
q.put(newword)
ans[newword] = ans[tmp] + 1
wordList.remove(newword)
return 0