第9课-深度优先搜索和广度优先搜索

搜索 - 遍历

  • 每个节点都要访问一次
  • 每个节点仅仅要访问一次
  • 对于节点的访问顺序不限
    • 深度优先:depth first search
    • 广度优先:breadth first search
def dfs(node):
   if node in visited:
     # already visited
     return
   visited.add(node)
   # process current node
   # ... # logic here
   dfs(node.left)
   dfs(node.right)

深度优先搜索 Depth-First-Search

遍历顺序

在这里插入图片描述
在这里插入图片描述

DFS 代码 - 递归写法

visited = set()
def dfs(node, visited):
  if node in visited: # terminator
      # already visited
return
   visited.add(node)
   # process current node here.
   ...
   for next_node in node.children():
      if not next_node in visited:
        dfs(next node, visited)

DFS 代码 - 非递归写法

def DFS(self, tree):
    if tree.root is None:
return []
    visited, stack = [], [tree.root]
    while stack:
       node = stack.pop()
       visited.add(node)
       process (node)
       nodes = generate_related_nodes(node)
       stack.push(nodes)
    # other processing work
...

广度优先搜索-Breadth-First-Search

遍历顺序

在这里插入图片描述
在这里插入图片描述

BFS 代码

def BFS(graph, start, end):
   queue = []
   queue.append([start])
   visited.add(start)
   while queue:
       node = queue.pop()
       visited.add(node)
       process(node)
       nodes = generate_related_nodes(node)
       queue.push(nodes)
   # other processing work
...

实战题目

  1. https://leetcode-cn.com/problems/binary-tree-level-order-traversal/#/description
  2. https://leetcode-cn.com/problems/minimum-genetic-mutation/#/description
  3. https://leetcode-cn.com/problems/generate-parentheses/#/description
  4. https://leetcode-cn.com/problems/find-largest-value-in-each-tree-row/#/description

Homework

  1. https://leetcode-cn.com/problems/word-ladder/description/
  2. https://leetcode-cn.com/problems/word-ladder-ii/description/
  3. https://leetcode-cn.com/problems/number-of-islands/
  4. https://leetcode-cn.com/problems/minesweeper/description/
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值