LeetCode-广度优先搜索-Hard

记录了初步解题思路 以及本地实现代码;并不一定为最优 也希望大家能一起探讨 一起进步




126. word-ladder-ii 单词接龙 II

解题思路:根据转换次数将单词分级
根据层级来处理单词
去除已在层级中的单词
同时 使用premap每一个单词记录上一层级变换到自己的父单词
list变为set减少耗时
当找到endword后 可以根据premap从最后一个endword从后往前遍历出所有可能性 getpath

def ladderLength(beginWord, endWord, wordList):
    """
    :type beginWord: str
    :type endWord: str
    :type wordList: List[str]
    :rtype: List[List[str]]
    """
    wordlist = set(wordList)
    def getpath(path,word):
        if len(preMap.get(word,[])) == 0:
            ret.append([word] + path)
            return
        path = [word]+path
        for w in preMap[word]:
            getpath(path[:],w)
        path.pop(0)

    length = len(beginWord)
    preMap = {}
    for word in wordList:
        preMap[word] = []
    ret = []
    cur_level = set()
    cur_level.add(beginWord)
    while True:
        pre_level = cur_level
        cur_level = set()
        for word in pre_level: 
            if word in wordList:
                wordList.remove(word)
        for word in pre_level:
            for i in range(length):
                left = word[:i]
                right = word[i+1:]
                for c in 'abcdefghijklmnopqrstuvwxyz':
                    if c != word[i]:
                        nextWord = left + c + right
                        if nextWord in wordList:
                            preMap[nextWord].append(word)
                            cur_level.add(nextWord)
        if len(cur_level) == 0:
            return []
        if endWord in cur_level:
            break
    getpath([],endWord)
    return ret

407.trapping-rain-water-ii

解题思路:

  1. 边界最大水深即为边界平台高度,加入队列
  2. 出队一个平台i,更新邻接点j水面深度,如果更新成功则将邻接点入队
    更新规则:limit=max(heightMap[j],h[i]),h[j] > limit
  3. 统计最终平台水面高度-平台高度之和
def trapRainWater(heightMap):
    """
    :type heightMap: List[List[int]]
    :rtype: int
    """
    x = len(heightMap)
    if x <=2 :
        return 0
    y = len(heightMap[0])

    fullMap = [[float('inf')] * y for _ in range(x)]
    deallist = []
    for i in range(x):
        for j in range(y):
            if i in (0, x - 1) or j in (0, y - 1):
                fullMap[i][j] = heightMap[i][j]
                deallist.append((i, j))

    while deallist:
        i, j= deallist.pop(0)
        for dx, dy in zip((1, 0, -1, 0), (0, 1, 0, -1)):
            nx, ny = i + dx, j + dy
            if nx <= 0 or nx >= x - 1 or ny <= 0 or ny >= y - 1: continue
            limit = max(fullMap[i][j], heightMap[nx][ny])
            #print(nx,ny,fullMap,fullMap[i][j], heightMap[nx][ny],limit)
            if fullMap[nx][ny] > limit:
                fullMap[nx][ny] = limit
                deallist.append((nx, ny))
    print(fullMap)
    print(heightMap)
    return sum(fullMap[i][j] - heightMap[i][j] for i in range(x) for j in range(y))

猜你喜欢

转载自blog.csdn.net/zkt286468541/article/details/84196930