当前位置: 首页 > 后端技术 > Python

leetcode127.WordSolitaire126.WordSolitaireII

时间:2023-03-26 01:08:57 Python

127.WordSolitaire126.WordSolitaireII预处理+广度优先遍历这段代码没有超时,但是速度很慢。官方问题解释可以使用双向宽搜索来提高速度。我这里没有写双向代码。127问题类解决方案:defladderLength(self,beginWord:str,endWord:str,wordList:List[str])->int:ifbeginWordnotinwordList:wordList.append(beginWord)ifendWordnotinwordList:return0s=wordList.index(beginWord)e=wordList.index(endWord)f=[False]*len(wordList)导入队列q=queue.Queue()f[s]=Trueq.put((s,0,[]))edges={}fori,wordinenumerate(wordList):w=list(word)forjinrange(len(w)):t=w[j]w[j]='*'ww=''.join(w)ifwwnotinedges:edges[ww]=[]edges[ww].append(i)w[j]=tmins=-1#ans=[]whilenotq.empty():cur,step,path=q.get()path.append(wordList[cur])f[cur]=Trueifcur==e:ifmins==-1:mins=stepreturnstep+1#else:#ifminsList[List[str]]:如果beginWord不在wordList中:wordList.append(beginWord)如果endWord不在wordList中:return[]s=wordList.index(beginWord)e=wordList.index(endWord)f=[假]*len(wordList)导入队列q=queue.Queue()f[s]=Trueq.put((s,0,[]))edges={}fori,wordinenumerate(wordList):w=list(word)forjinrange(len(w)):t=w[j]w[j]='*'ww=''.join(w)如果ww不在边上:edges[ww]=[]edges[ww.append(i)w[j]=tmins=-1ans=[]whilenotq.empty():cur,step,path=q.get()path.append(wordList[cur])f[cur]=Trueifcur==e:ifmins==-1:mins=stepelse:ifminsint:如果beginWord不在wordList中:wordList.append(beginWord)如果endWord不在wordList中:return0#wordList.append(endWord)s=wordList.index(beginWord)e=wordList.index(endWord)f=[False]*len(wordList)importqueueq=queue.Queue()f[s]=Trueq.put((s,0,[]))defcan_go(w1,w2):c=0assertlen(w1)==len(w2)foriinrange(len(w1)):ifw1[i]!=w2[i]:c+=1ifc>1:returnFalsereturnc==1mins=-1whilenotq.empty():cur,step,path=q.get()path.append(wordList[cur])f[cur]=Trueifcur==e:ifmins==-1:mins=stepreturnstep+1fori在范围内(len(wordList)):如果i!=cur而不是f[i]:ifcan_go(wordList[cur],wordList[i]):q.put((i,step+1,path[::]))return0欢迎来到我的博客:https://codeplot.top/我的博客分类:https://codeplot.top/categories/%E5%88%B7%E9%A2%98/