BFS算法模板(python实现)
BFS算法整理(python实现)
广度优先算法(Breadth-First-Search),简称BFS,是一种图形搜索演算算法。
1. 算法的应用场景
2. 算法的模板
2.1 针对树的BFS模板
- 无需分层遍历
from collections import deque
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def level_order_tree(root, result):
if not root:
return
# 这里借助python的双向队列实现队列
# 避免使用list.pop(0)出站的时间复杂度为O(n)
queue = deque([root])
while queue:
node = queue.popleft()
# do somethings
result.append(node.val)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
return result
if __name__ == "__main__":
tree = TreeNode(4)
tree.left = TreeNode(9)
tree.right = TreeNode(0)
tree.left.left = TreeNode(5)
tree.left.right = TreeNode(1)
print(level_order_tree(tree, []))
# [4, 9, 0, 5, 1]
- 需要分层遍历
def level_order_tree(root):
if not root:
return
q = [root]
while q:
new_q = []
for node in q:
# do somethins with this layer nodes...
# 判断左右子树
if node.left:
new_q.append(node.left)
if node.right:
new_q.append(node.right)
# 记得将旧的队列替换成新的队列
q = new_q
# 最后return想要返回的东西
return xxx
2.2 针对图的BFS
- 无需分层遍历的图
from collections import deque
def bsf_graph(root):
if not root:
return
# queue和seen为一对好基友,同时出现
queue = deque([root])
# seen避免图遍历过程中重复访问的情况,导致无法跳出循环
seen = set([root])
while queue:
head = queue.popleft()
# do somethings with the head node
# 将head的邻居都添加进来
for neighbor in head.neighbors:
if neighbor not in seen:
queue.append(neighbor)
seen.add(neighbor)
return xxx
- 需要分层遍历的图
def bsf_graph(root):
if not root:
return
queue = [root]
seen = set([root])
while queue:
new_queue = []
for node in queue:
# do somethins with the node
for neighbor in node.neighbors:
if neighbor not in seen:
new_queue.append(neighbor)
seen.add(neighbor)
return xxx
2.3 拓扑排序
在图论中,由一个有向无环图的顶点组成的序列,当且仅当满足下列条件时,称为该图的一个拓扑排序(英语:Topological sorting)。
每个顶点出现且只出现一次;
若A在序列中排在B的前面,则在图中不存在从B到A的路径。
实际应用
- 检测编译时的循环依赖
- 制定有依赖关系的任务的执行顺序(例如课程表问题)
算法流程
- 统计所有点的入度,并初始化拓扑排序序列为空。
- 将所有入度为0的点,放到如BFS初始的搜索队列中。
- 将队列中的点一个一个释放出来,把访问其相邻的点,并把这些点的入度-1.
- 如何发现某个点的入度为0时,则把这个点加入到队列中。
- 当队列为空时,循环结束。
算法实现
class Solution():
def top_sort(self, graph):
node_to_indegree = self.get_indegree(graph)
# 初始化拓扑排序序列为空
order = []
start_nodes = [node for node in graph if node_to_indegree[node] == 0]
queue = collection.deque(start_nodes)
while queue:
head = queue.popleft()
order.append(node)
for neighbor in head.neighbors:
node_to_indegree[neighbor] -= 1
if node_to_indegree[neighbor] == 0:
queue.append(neighbor)
return order
def get_indegree(self, graph):
node_to_indegree = {x: 0 for x in graph}
for node in graph:
for neighbor in node.neighbors:
node_to_indegree[neighbor] += 1
return node_to_indegree
BFS算法模板(python实现)的更多相关文章
- [笔记]BFS算法的python实现
#!/usr/bin/env python # -*- coding:utf-8 -*- graph = {} graph["you"] = ["alice", ...
- BFS (1)算法模板 看是否需要分层 (2)拓扑排序——检测编译时的循环依赖 制定有依赖关系的任务的执行顺序 djkstra无非是将bfs模板中的deque修改为heapq
BFS模板,记住这5个: (1)针对树的BFS 1.1 无需分层遍历 from collections import deque def levelOrderTree(root): if not ro ...
- BFS算法(——模板习题与总结)
首先需要说明的是BFS算法(广度优先算法)本质上也是枚举思想的一种体现,本身效率不是很高,当数据规模很小的时候还是可以一试的.其次很多人可能有这样的疑问,使用搜索算法的时候,到底选用DFS还是BFS, ...
- POJ 1273 Drainage Ditches(网络流dinic算法模板)
POJ 1273给出M条边,N个点,求源点1到汇点N的最大流量. 本文主要就是附上dinic的模板,供以后参考. #include <iostream> #include <stdi ...
- 机器学习算法与Python实践之(三)支持向量机(SVM)进阶
机器学习算法与Python实践之(三)支持向量机(SVM)进阶 机器学习算法与Python实践之(三)支持向量机(SVM)进阶 zouxy09@qq.com http://blog.csdn.net/ ...
- 算法模板学习专栏之总览(会慢慢陆续更新ing)
博主欢迎转载,但请给出本文链接,我尊重你,你尊重我,谢谢~http://www.cnblogs.com/chenxiwenruo/p/7495310.html特别不喜欢那些随便转载别人的原创文章又不给 ...
- POJ 1815 - Friendship - [拆点最大流求最小点割集][暴力枚举求升序割点] - [Dinic算法模板 - 邻接矩阵型]
妖怪题目,做到现在:2017/8/19 - 1:41…… 不过想想还是值得的,至少邻接矩阵型的Dinic算法模板get√ 题目链接:http://poj.org/problem?id=1815 Tim ...
- HDU1532最大流 Edmonds-Karp,Dinic算法 模板
Drainage Ditches Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others) To ...
- Day1 BFS算法的学习和训练
因为自己的原因,之前没有坚持做算法的相应学习,总是觉得太难就半途而废,真的算是一个遗憾了,所以现在开始,定一个30天入门学习算法计划. 我是根据<算法图解>的顺序进行安排的,自己对 ...
随机推荐
- C语言I 博客作业03
这个作业属于哪个课程 C语言程序设计II 这个作业要求在哪里 作业要求 我在这个课程的目标是 掌握关系运算.if-else语句.格式化输入语句scanf(),以及常用的数学库函数 这个作业在那个具体方 ...
- Java8-ConcurrentHashMap
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ForkJoinPool; public clas ...
- 022_统计每个远程 IP 访问了本机 apache 几次?
#$1为IP#i为不同的IP#print ip[i],i 输出不同IP出现的次数总和以及它们是谁#ip[$1]++ 未定义则从0开始,IP出现则自增 #!/bin/bashawk '{ip[$1]++ ...
- [Luogu] 高斯消元法
https://www.luogu.org/problemnew/show/P3389 模拟,消元 #include <bits/stdc++.h> #define DB double ; ...
- UVA 11754 Code Feat 中国剩余定理+枚举
Code FeatUVA - 11754 题意:给出c个彼此互质的xi,对于每个xi,给出ki个yj,问前s个ans满足ans%xi的结果在yj中有出现过. 一看便是个中国剩余定理,但是同余方程组就有 ...
- c isnormal
Returns whether x is a normal value: i.e., whether it is neither infinity, NaN, zero or subnormal. / ...
- shell 字符串分割cut
cut 选项与参数 -d:后面接分隔字符.与-f一起使用. -f:依据-d的分隔字符将一段信息分隔数段,用-f取出第几段的意思. -c:以字符的单位取出固定字符区间 [zhang@localhost ...
- cesium billboard跨域问题1
群里小伙伴问道使用billboard加载图片时出现跨域问题,一般认为在服务器端设置 Access-Control-Allow-Origin: * 例如用tomcat发布图片服务,可以这样设置:http ...
- 解决Maven的jar包冲突问题
1. 问题描述 控制台说:无法将 com.zpx.servlet.MyServlet 识别为 javax.servlet.Servlet 2. 问题原因 Maven的一个核心功能就是一键构建,所以Ma ...
- Linux设备驱动程序 之 内存池
内核中有些地方的内存分配是不允许失败的,为了确保这种情况下的成功分配,内核开发者建立了一种称为内存池的抽象:内存池其实就是某种形式的后备高速缓存,它试图始终保存空闲的内存,以便在紧急状态下使用: me ...