LeetCode-广度优先搜索-Medium

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


文章目录

      • 102. 二叉树的层次遍历 Binary-Tree-Level-Order-Traversal
      • 103. 二叉树的锯齿形层次遍历 binary-tree-zigzag-level-order-traversal
      • 127. 单词接龙 Word-Ladder
      • 130. 被围绕的区域 surrounded-regions
      • 199. 二叉树的右视图 binary-tree-right-side-view
      • 200. 岛屿的个数 number-of-islands


102. 二叉树的层次遍历 Binary-Tree-Level-Order-Traversal

解题思路:将节点放入队列中,同时记录每个节点的层级,当处理的节点层级增加时,可将前一层次的节点保存

def levelOrder(root):
    """
    :type root: TreeNode
    :rtype: List[List[int]]
    """
    ret =[]
    if root==None:
        return ret
    nodelist = [(root,0)]
    
    while len(nodelist)>0:
        node,level = nodelist[0]
        if level <= len(ret)-1:
            res = ret[level]
            res.append(node.val)
            ret[level] = res
        else:
            res = [node.val]
            ret.append(res)
        nodelist.pop(0)
        if node.left:
            nodelist.append((node.left,level+1))
        if node.right:
            nodelist.append((node.right,level+1))
        
        
    return ret

103. 二叉树的锯齿形层次遍历 binary-tree-zigzag-level-order-traversal

解题思路:思路与102相同 在添加层次时 关注其奇偶

def zigzagLevelOrder(root):
    """
    :type root: TreeNode
    :rtype: List[List[int]]
    """    
    if not root:
        return []
    l =[]
    l.append((root,0))
    tmpl=[]
    tmp=0
    ret=[]
    while len(l)>0:
        v,level = l.pop(0)
        if tmp==level:
            tmpl.append(v.val)
        else:
            print(level)
            if level%2==0:
                print("down")
                tmpl.reverse()
            ret.append(tmpl)
            tmpl=[v.val]
            tmp=level
        if v.left:
            l.append((v.left,level+1))
        if v.right:
            l.append((v.right,level+1))
    if level%2==1:
        tmpl.reverse()
    ret.append(tmpl)
    return ret

127. 单词接龙 Word-Ladder

解题思路:将当前词语可以转变的下一个单词放入队列中 同时使用一个dict记录到达该单词需要转变的次数
当第一次遇到endword时 即刻返回
为了减少耗时 将list转换为set

def ladderLength(beginWord, endWord, wordList):
    """
    :type beginWord: str
    :type endWord: str
    :type wordList: List[str]
    :rtype: int
    """
    wordList = set(wordList)
    if endWord not in wordList:
        return 0
    ans ={}
    ans[beginWord] = 1
    l = []
    l.append(beginWord)
   
    if beginWord in wordList:
        wordList.remove(beginWord)
    
    while len(l)>0:
        tmp = l.pop(0)
        if tmp == endWord:
            return ans[tmp]
        for i in range(len(tmp)):
            part1,part2 = tmp[:i],tmp[i+1:]
            for j in 'abcdefghijklmnopqrstuvwxyz':
                if tmp[i] != j:
                    newword = part1 + j + part2
                    if newword in wordList:
                        l.append(newword)
                        ans[newword] = ans[tmp] + 1
                        wordList.remove(newword)
    return 0

130. 被围绕的区域 surrounded-regions

解题思路:未被包围的区域必定连通到边上
找到四条边上未被包围的点 从这些点出发寻找未被包围的区块
con用来存储未被包围的点 find用来寻找连通的下一个点

def solve(board):
    """
    :type board: List[List[str]]
    :rtype: void Do not return anything, modify board in-place instead.
    """
    x = len(board)
    if x==0:
        return
    y = len(board[0])
    con = set()
    
    def find(i,j):
        if board[i][j]=="X" or (i,j) in con:
            return    
        con.add((i,j))  
        if i>0:
            find(i-1,j)
        if j>0:
            find(i,j-1)
        if i<x-1:
            find(i+1,j)
        if j<y-1:
            find(i,j+1)
            
    for i in [0,x-1]:
        for j in range(y):
            if board[i][j]=="O" and (i,j) not in con:
                find(i,j)
    print(con)
    for j in [0,y-1]:
        for i in range(x):
            if board[i][j]=="O":
                con.add((i,j))
                find(i,j)
                
    for i in range(x):
        for j in range(y):
            if (i,j) not in con:
                board[i][j]="X"
    return board

199. 二叉树的右视图 binary-tree-right-side-view

解题思路:将节点放入队列中
记录上一个点的层级 和值
只是当节点层次变化时 即上一个点为上一层的最右侧节点

def rightSideView(root):
    """
    :type root: TreeNode
    :rtype: List[int]
    """
    ret =[]
    if not root:
        return ret
    
    l=[]
    l.append((root,0))
    last = root.val
    lastl = 0
    while len(l)>0:
        node,level=l.pop(0)
        if node.left:
            l.append((node.left,level+1))
        if node.right:
            l.append((node.right,level+1))
        if lastl < level:
            ret.append(last)
        last = node.val
        lastl = level
    ret.append(last)
    return ret

200. 岛屿的个数 number-of-islands

解题思路:从一处陆地出发 搜索他能到达的所有陆地处 搜索过的陆地变为水
重新开始一处新的陆地时 岛屿数量+1

def numIslands(grid):
    """
    :type grid: List[List[str]]
    :rtype: int
    """
    x = len(grid)
    if x==0:
        return 0
    y = len(grid[0])
    island = set()
    def find(i,j):
        if i<0 or j<0 or i==x or j==y or grid[i][j]=="0" or (i,j) in island:
            return
        grid[i][j] = "0"
        island.add((i,j))
        find(i-1,j)
        find(i,j-1)
        find(i+1,j)
        find(i,j+1)
        
    ret = 0
    for i in range(x):
        for j in range(y):
            if grid[i][j]=="1":
                ret +=1
                find(i,j)
    return ret

你可能感兴趣的:(Exercise,LeetCode,广度优先搜索,medium)