题目:
给定一个开始字符串beginWord 如 ‘hit’,结束字符串endWord如‘cog’,字符串字典wordlist 如 ["hot","dot","dog","lot","log","cog"]。从开始字符串开始,要求每次只能改变一个字符,求经过wordlist到达endWord的最短路径
解题思路:
考虑到最短路径,用djistra算法,从开始字符串出发,找到该字符串改变一个字符后可以到达wordlist中的所有字符串。再从新到达的字符串列表出发,计算一步之后可以到达wordlist中之前未到达的所有字符串。经过多次循环,直到新到达的字符串中包含结束字符串,返回当前步数即可。
注意:
这是一个非常卡时间的题目。需要将原始的字符串字典wordlist存为python中的字典格式,减少搜索的复杂度(从n到1)
代码如下(leetcode中AC):
class Solution(object):
def ladderLength(self, beginWord, endWord, wordList):
"""
:type beginWord: str
:type endWord: str
:type wordList: List[str]
:rtype: int
"""
character = 'abcdefghijklmnopqrstuvwxyz'
def dijkstra(new_list,unreached_list,endWord,count):
if unreached_list==[] or new_list==[]:
return 0
count = count + 1
list_return = []
for i in range(len(new_list)):
for j in range(len(new_list[i])):
for k in character:
temp = new_list[i]
tmp1 = temp[:j]
tmp2 = temp[j+1:]
temp = tmp1+k+tmp2
if temp==new_list[i][j]:
continue
else:
if temp in unreached_list:
list_return.append(temp)
if temp==endWord:
return count
del unreached_list[temp]
return dijkstra(list_return,unreached_list,endWord,count)
begin = []
begin.append(beginWord)
dict_unreach = {}
for i in range(len(wordList)):
if wordList[i] not in dict_unreach:
dict_unreach[wordList[i]] = 1
return dijkstra(begin,dict_unreach,endWord,1)