预处理+广度优先遍历
这个代码不超时了,但是十分缓慢,官方题解说可以使用双向广搜提高速度,我这里没有写双向的代码
127 题
class Solution:
def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int:
if beginWord not in wordList:
wordList.append(beginWord)
if endWord not in wordList:
return 0
s = wordList.index(beginWord)
e = wordList.index(endWord)
f = [False] * len(wordList)
import queue
q = queue.Queue()
f[s] = True
q.put((s, 0, []))
edges = {}
for i, word in enumerate(wordList):
w = list(word)
for j in range(len(w)):
t = w[j]
w[j] = '*'
ww = ''.join(w)
if ww not in edges:
edges[ww] = []
edges[ww].append(i)
w[j] = t
mins = -1
# ans = []
while not q.empty():
cur, step, path = q.get()
path.append(wordList[cur])
f[cur] = True
if cur == e:
if mins == -1:
mins = step
return step+1
# else:
# if mins < step:
# return ans
# ans.append(path)
w = list(wordList[cur])
for j in range(len(w)):
t = w[j]
w[j] = '*'
ww = ''.join(w)
for x in edges[ww]:
if f[x] == False:
q.put((x, step+1, path[::]))
w[j] = t
return 0
126 题
class Solution:
def findLadders(self, beginWord: str, endWord: str, wordList: List[str]) -> List[List[str]]:
if beginWord not in wordList:
wordList.append(beginWord)
if endWord not in wordList:
return []
s = wordList.index(beginWord)
e = wordList.index(endWord)
f = [False] * len(wordList)
import queue
q = queue.Queue()
f[s] = True
q.put((s, 0, []))
edges = {}
for i, word in enumerate(wordList):
w = list(word)
for j in range(len(w)):
t = w[j]
w[j] = '*'
ww = ''.join(w)
if ww not in edges:
edges[ww] = []
edges[ww].append(i)
w[j] = t
mins = -1
ans = []
while not q.empty():
cur, step, path = q.get()
path.append(wordList[cur])
f[cur] = True
if cur == e:
if mins == -1:
mins = step
else:
if mins < step:
return ans
ans.append(path)
w = list(wordList[cur])
for j in range(len(w)):
t = w[j]
w[j] = '*'
ww = ''.join(w)
for x in edges[ww]:
if f[x] == False:
q.put((x, step+1, path[::]))
w[j] = t
return ans
超时代码
127 题
class Solution:
def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int:
if beginWord not in wordList:
wordList.append(beginWord)
if endWord not in wordList:
return 0
# wordList.append(endWord)
s = wordList.index(beginWord)
e = wordList.index(endWord)
f = [False] * len(wordList)
import queue
q = queue.Queue()
f[s] = True
q.put((s, 0, []))
def can_go(w1, w2):
c = 0
assert len(w1) == len(w2)
for i in range(len(w1)):
if w1[i] != w2[i]:
c += 1
if c > 1:
return False
return c == 1
mins = -1
while not q.empty():
cur, step, path = q.get()
path.append(wordList[cur])
f[cur] = True
if cur == e:
if mins == -1:
mins = step
return step+1
for i in range(len(wordList)):
if i != cur and not f[i]:
if can_go(wordList[cur], wordList[i]):
q.put((i, step+1, path[::]))
return 0
欢迎来我的博客: https://codeplot.top/
我的博客刷题分类:https://codeplot.top/categories/%E5%88%B7%E9%A2%98/
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。