Leecode: the second word of the Dragon (Python)

A good function 2020-11-13 02:57:11
leecode second word dragon python


1. Title Description

Give two words (beginWord and endWord) And a dictionary wordList, Find out all the beginWord To endWord The shortest conversion sequence of . The conversion should follow the following rules :

Only one letter can be changed at a time .
The middle word in the conversion process must be the word in the dictionary .

explain :
If there is no such conversion sequence , Return an empty list .
All words have the same length .
All words consist of lowercase letters only .
There are no duplicate words in the dictionary .
You can assume beginWord and endWord It's not empty , And they are different .
Example 1:
Input :
beginWord = “hit”,
endWord = “cog”,
wordList = [“hot”,“dot”,“dog”,“lot”,“log”,“cog”]
Output :
[
[“hit”,“hot”,“dot”,“dog”,“cog”],
[“hit”,“hot”,“lot”,“log”,“cog”]
]
Example 2:
Input :
beginWord = “hit”
endWord = “cog”
wordList = [“hot”,“dot”,“dog”,“lot”,“log”]
Output : []
explain : endWord “cog” Not in the dictionary , So there is no conversion sequence that meets the requirements .

2. Ideas

For three days , Refer to other people's ideas , I tried it several times , finally AC 了 .
The specific purpose of each code is annotated in the code .

This is an advanced version of word solitaire , To return all the conversion sequences . Here I draw on Nanguo Ziqi The idea of .
By way of example 1 For example :
beginWord = “hit”,
endWord = “cog”,
wordList = [“hot”,“dot”,“dog”,“lot”,“log”,“cog”]
say concretely , The main work is as follows :
 Insert picture description here

  1. Set up with a dictionary beginWord and endWord The connection between words , Among them, the dictionary of key It's the following word ,val yes key An array of words made up of the preceding words . Such as :hot The first word of is hit. When key by beginWord when ,val by [], The dictionary created by this example is memories = {“cog”:[“log”,“dog”], “log”:[“lot”], “dog”:[“dot”], “dot”:[“hot”], “lot”:[“hot”], “hot”:[“hit”],“hit”:[]}.
  2. According to the constructed Dictionary , Make use of... With backtracking dfs Method generation from beginWord To endWord The transformation path of .
  3. When building dictionaries , We can use hierarchical traversal , With the help of two sets ,preset and curset. among preset In the collection are the words from the previous layer ,curset Represents the set of words in the current layer . namely curset The word in is key,preset The word in it is value, When the loop starts , This time the cycle is curset It's the next cycle preset, To avoid repetition , At the end of each cycle , We have to put curset The words in are from wordList Removing the ( Or put... Before the loop preset Take out the words in ).

2.1 python Code

class Solution:
def findLadders(self, beginWord: str, endWord: str, wordList: List[str]) -> List[List[str]]:
# utilize dfs Build path 
def buildPath(path,word):
# dfs Construct from a dictionary beginWord To endWord The path of , Where the path generation function is from endWord Back and forth 
if len(memories[word]) == 0:
# Because if the dictionary is built , In the whole path ,
# Only beginWord Of val yes [], All the others have at least one word ,
# Otherwise, it will not form a complete path .
# It is necessary to put word Added to the path Head ( Because it's backward ) And press it into the results 
res.append([word] + path)
return
# If not beginWord, Insert it into path Head , And then go to the next level of the word .
# Because there may be more than one word changing one letter to get the current word , Using a for loop ,
# Read the word above the word from the dictionary , Recursion separately .
path.insert(0,word)
for element in memories[word]:
buildPath(path,element)
# Because there may be more than one path ( There are more than one word at the top of a word , Or there are more than one underlying word in a word ) 
# So you need to take out the elements that are inserted into the head .( to flash back ), Every operation ( recursive ) once , Just take out an element .
# Make path Back to for Before the loop path.
path.pop(0)
# Two : Build a dictionary 
memories = {
}
memories[beginWord] = [] # take beginWord Of val Value is set to []
wordList = set(wordList) # Because it doesn't repeat , First pair wordList Do weight reduction .
wordList.discard(beginWord) # take beginWord from wordList Delete in 
# Initialize first memories, Make it key by wordList The words in ,val Set unified to []
for i in wordList:
memories[i] = []
# With the help of two sets (preset and curset) Store the words of the previous layer and the words of the current layer 
curset = set()
curset.add(beginWord)
preset = set()
lenth = len(beginWord)
res = []
while True:
preset = curset # Last cycle curset Become this cycle of precut.
# because curset It is used to store the current layer elements of this loop , So before each cycle ,
# All of them will curset Empty again , To fill in the current layer elements 
curset = set()
# Judge the words in the upper layer , See if there's still wordList The words in ,
# It can be obtained from a change of words on the upper layer . Some words , Just modify the corresponding in the dictionary key Of val value .
# At the same time, press the word into curset( Current layer )
for preword in preset:
for i in range(lenth):
left = preword[:i]
right = preword[i+1:]
for byte in "abcdefghijklmnopqrstuvwxyz":
if byte != preword[i]:
tempword = left + byte + right
if tempword in wordList:
memories[tempword].append(preword)
curset.add(tempword)
# To avoid repetition , At the end of each examination , You need to change the current level words from wordList Delete in ,
# Otherwise, the next level of elements in the next loop , There should be no reuse .
for word in curset:
wordList.discard(word)
# When building dictionaries , If all the elements in the upper layer can't go through one change 
# obtain wordList The words in ), It means that the path will break , I can't find it from begin To end The path of 
# No more checking , Go straight back to []. Of course, there may be other words in the dictionary val It's empty ,
# As long as it's not on the path, it doesn't affect .( Not in precut in )
if len(curset) == 0:
return []
# If endWord stay curset in , namely endWord Is the current layer word of the current loop ,
# State that it has arrived endWord 了 , Just break the loop .endWord It won't be the next level element of any word .
if endWord in curset:
break
buildPath([],endWord) # Build the dictionary as a path and return the result 
return res
版权声明
本文为[A good function]所创,转载请带上原文链接,感谢

  1. 利用Python爬虫获取招聘网站职位信息
  2. Using Python crawler to obtain job information of recruitment website
  3. Several highly rated Python libraries arrow, jsonpath, psutil and tenacity are recommended
  4. Python装饰器
  5. Python实现LDAP认证
  6. Python decorator
  7. Implementing LDAP authentication with Python
  8. Vscode configures Python development environment!
  9. In Python, how dare you say you can't log module? ️
  10. 我收藏的有关Python的电子书和资料
  11. python 中 lambda的一些tips
  12. python中字典的一些tips
  13. python 用生成器生成斐波那契数列
  14. python脚本转pyc踩了个坑。。。
  15. My collection of e-books and materials about Python
  16. Some tips of lambda in Python
  17. Some tips of dictionary in Python
  18. Using Python generator to generate Fibonacci sequence
  19. The conversion of Python script to PyC stepped on a pit...
  20. Python游戏开发,pygame模块,Python实现扫雷小游戏
  21. Python game development, pyGame module, python implementation of minesweeping games
  22. Python实用工具,email模块,Python实现邮件远程控制自己电脑
  23. Python utility, email module, python realizes mail remote control of its own computer
  24. 毫无头绪的自学Python,你可能连门槛都摸不到!【最佳学习路线】
  25. Python读取二进制文件代码方法解析
  26. Python字典的实现原理
  27. Without a clue, you may not even touch the threshold【 Best learning route]
  28. Parsing method of Python reading binary file code
  29. Implementation principle of Python dictionary
  30. You must know the function of pandas to parse JSON data - JSON_ normalize()
  31. Python实用案例,私人定制,Python自动化生成爱豆专属2021日历
  32. Python practical case, private customization, python automatic generation of Adu exclusive 2021 calendar
  33. 《Python实例》震惊了,用Python这么简单实现了聊天系统的脏话,广告检测
  34. "Python instance" was shocked and realized the dirty words and advertisement detection of the chat system in Python
  35. Convolutional neural network processing sequence for Python deep learning
  36. Python data structure and algorithm (1) -- enum type enum
  37. 超全大厂算法岗百问百答(推荐系统/机器学习/深度学习/C++/Spark/python)
  38. 【Python进阶】你真的明白NumPy中的ndarray吗?
  39. All questions and answers for algorithm posts of super large factories (recommended system / machine learning / deep learning / C + + / spark / Python)
  40. [advanced Python] do you really understand ndarray in numpy?
  41. 【Python进阶】Python进阶专栏栏主自述:不忘初心,砥砺前行
  42. [advanced Python] Python advanced column main readme: never forget the original intention and forge ahead
  43. python垃圾回收和缓存管理
  44. java调用Python程序
  45. java调用Python程序
  46. Python常用函数有哪些?Python基础入门课程
  47. Python garbage collection and cache management
  48. Java calling Python program
  49. Java calling Python program
  50. What functions are commonly used in Python? Introduction to Python Basics
  51. Python basic knowledge
  52. Anaconda5.2 安装 Python 库(MySQLdb)的方法
  53. Python实现对脑电数据情绪分析
  54. Anaconda 5.2 method of installing Python Library (mysqldb)
  55. Python implements emotion analysis of EEG data
  56. Master some advanced usage of Python in 30 seconds, which makes others envy it
  57. python爬取百度图片并对图片做一系列处理
  58. Python crawls Baidu pictures and does a series of processing on them
  59. python链接mysql数据库
  60. Python link MySQL database