DFS and BFS
DFS
https://leetcode.com/problems/binary-tree-paths/#/solutions
Nodes and References Implementation of a Tree
class BinaryTree(object):
def __init__(self,rootObj):
self.key = rootObj
self.leftChild = None
self.rightChild = None def insertLeft(self,newNode):
if self.leftChild == None:
self.leftChild = BinaryTree(newNode)
else:
t = BinaryTree(newNode)
t.leftChild = self.leftChild
self.leftChild = t def insertRight(self,newNode):
if self.rightChild == None:
self.rightChild = BinaryTree(newNode)
else:
t = BinaryTree(newNode)
t.rightChild = self.rightChild
self.rightChild = t def getRightChild(self):
return self.rightChild def getLeftChild(self):
return self.leftChild def setRootVal(self,obj):
self.key = obj def getRootVal(self):
return self.key
Implementation of Depth-First Search
This algorithm we will be discussing is Depth-First search which as the name hints at, explores possible vertices (from a supplied root) down each branch before backtracking. This property allows the algorithm to be implemented succinctly in both iterative and recursive forms. Below is a listing of the actions performed upon each visit to a node.
- Mark the current vertex as being visited.
- Explore each adjacent vertex that is not included in the visited set.
We will assume a simplified version of a graph in the following form:
graph = {'A': set(['B', 'C']),
'B': set(['A', 'D', 'E']),
'C': set(['A', 'F']),
'D': set(['B']),
'E': set(['B', 'F']),
'F': set(['C', 'E'])}
Connected Component
The implementation below uses the stack data-structure to build-up and return a set of vertices that are accessible within the subjects connected component. Using Python’s overloading of the subtraction operator to remove items from a set, we are able to add only the unvisited adjacent vertices.
def dfs(graph, start, visited=None):
if visited is None:
visited = set()
visited.add(start)
for nxt in graph[start] - visited:
dfs(graph, nxt, visited)
return visited dfs(graph, 'A')
{'A', 'B', 'C', 'D', 'E', 'F'}
The second implementation provides the same functionality as the first, however, this time we are using the more succinct recursive form. Due to a common Python gotcha with default parameter values being created only once, we are required to create a new visited set on each user invocation. Another Python language detail is that function variables are passed by reference, resulting in the visited mutable set not having to reassigned upon each recursive call.
def dfs(graph, start, visited=None):
if visited is None:
visited = set()
visited.add(start)
for nxt in graph[start] - visited:
dfs(graph, nxt, visited)
return visited dfs(graph, 'A')
{'A', 'B', 'C', 'D', 'E', 'F'}
Paths
We are able to tweak both of the previous implementations to return all possible paths between a start and goal vertex. The implementation below uses the stack data-structure again to iteratively solve the problem, yielding each possible path when we locate the goal. Using a generator allows the user to only compute the desired amount of alternative paths.
def dfs_paths(graph, start, goal):
stack = [(start, [start])]
while stack:
(vertex, path) = stack.pop()
for nxt in graph[vertex] - set(path):
if nxt == goal:
yield path + [nxt]
else:
stack.append((nxt, path + [nxt])) list(dfs_paths(graph, 'A', 'F'))
[['A', 'B', 'E', 'F'], ['A', 'C', 'F']]
Implementation of Breadth First Search
An alternative algorithm called Breath-First search provides us with the ability to return the same results as DFS but with the added guarantee to return the shortest-path first. This algorithm is a little more tricky to implement in a recursive manner instead using the queue data-structure, as such I will only being documenting the iterative approach. The actions performed per each explored vertex are the same as the depth-first implementation, however, replacing the stack with a queue will instead explore the breadth of a vertex depth before moving on. This behavior guarantees that the first path located is one of the shortest-paths present, based on number of edges being the cost factor.
We'll assume our Graph is in the form:
graph = {'A': set(['B', 'C']),
'B': set(['A', 'D', 'E']),
'C': set(['A', 'F']),
'D': set(['B']),
'E': set(['B', 'F']),
'F': set(['C', 'E'])}
Connected Component
Similar to the iterative DFS implementation the only alteration required is to remove the next item from the beginning of the list structure instead of the stacks last.
def bfs(graph, start):
visited, queue = set(), [start]
while queue:
vertex = queue.pop(0)
if vertex not in visited:
visited.add(vertex)
queue.extend(graph[vertex] - visited)
return visited bfs(graph, 'A')
{'A', 'B', 'C', 'D', 'E', 'F'}
Paths
This implementation can again be altered slightly to instead return all possible paths between two vertices, the first of which being one of the shortest such path.
def bfs_paths(graph, start, goal):
queue = [(start, [start])]
while queue:
(vertex, path) = queue.pop(0)
for next in graph[vertex] - set(path):
if next == goal:
yield path + [next]
else:
queue.append((next, path + [next])) list(bfs_paths(graph, 'A', 'F'))
[['A', 'C', 'F'], ['A', 'B', 'E', 'F']]
Knowing that the shortest path will be returned first from the BFS path generator method we can create a useful method which simply returns the shortest path found or ‘None’ if no path exists. As we are using a generator this in theory should provide similar performance results as just breaking out and returning the first matching path in the BFS implementation.
def shortest_path(graph, start, goal):
try:
return next(bfs_paths(graph, start, goal))
except StopIteration:
return None shortest_path(graph, 'A', 'F')
['A', 'C', 'F']
DFS and BFS的更多相关文章
- Clone Graph leetcode java(DFS and BFS 基础)
题目: Clone an undirected graph. Each node in the graph contains a label and a list of its neighbors. ...
- 数据结构(12) -- 图的邻接矩阵的DFS和BFS
//////////////////////////////////////////////////////// //图的邻接矩阵的DFS和BFS ////////////////////////// ...
- 数据结构(11) -- 邻接表存储图的DFS和BFS
/////////////////////////////////////////////////////////////// //图的邻接表表示法以及DFS和BFS //////////////// ...
- 在DFS和BFS中一般情况可以不用vis[][]数组标记
开始学dfs 与bfs 时一直喜欢用vis[][]来标记有没有访问过, 现在我觉得没有必要用vis[][]标记了 看代码 用'#'表示墙,'.'表示道路 if(所有情况都满足){ map[i][j]= ...
- 图论中DFS与BFS的区别、用法、详解…
DFS与BFS的区别.用法.详解? 写在最前的三点: 1.所谓图的遍历就是按照某种次序访问图的每一顶点一次仅且一次. 2.实现bfs和dfs都需要解决的一个问题就是如何存储图.一般有两种方法:邻接矩阵 ...
- 图论中DFS与BFS的区别、用法、详解?
DFS与BFS的区别.用法.详解? 写在最前的三点: 1.所谓图的遍历就是按照某种次序访问图的每一顶点一次仅且一次. 2.实现bfs和dfs都需要解决的一个问题就是如何存储图.一般有两种方法:邻接矩阵 ...
- 数据结构基础(21) --DFS与BFS
DFS 从图中某个顶点V0 出发,访问此顶点,然后依次从V0的各个未被访问的邻接点出发深度优先搜索遍历图,直至图中所有和V0有路径相通的顶点都被访问到(使用堆栈). //使用邻接矩阵存储的无向图的深度 ...
- dfs和bfs的区别
详见转载博客:https://www.cnblogs.com/wzl19981116/p/9397203.html 1.dfs(深度优先搜索)是两个搜索中先理解并使用的,其实就是暴力把所有的路径都搜索 ...
- 邻接矩阵实现图的存储,DFS,BFS遍历
图的遍历一般由两者方式:深度优先搜索(DFS),广度优先搜索(BFS),深度优先就是先访问完最深层次的数据元素,而BFS其实就是层次遍历,每一层每一层的遍历. 1.深度优先搜索(DFS) 我一贯习惯有 ...
- 判断图连通的三种方法——dfs,bfs,并查集
Description 如果无向图G每对顶点v和w都有从v到w的路径,那么称无向图G是连通的.现在给定一张无向图,判断它是否是连通的. Input 第一行有2个整数n和m(0 < n,m < ...
随机推荐
- CSAcademy Beta Round #3 a-game
题目连接 a-game 大意:有一个只包含A和B的字符串,两个人分别取这个串的子串,但是每一次取不能与之前取到过的子串有交集,最后谁取到的所有串中A的总数量少的判为胜.如果一样,则为平手. 给出这样的 ...
- 不完全图解HTTP
在2D平面上行走的时候,认识只局限于“点”,刚认识一个新的点,就把之前的那个点忘记了,捡了芝麻丢西瓜.只从3D视角俯瞰时,把这些点连接在一起,点成线,线成面时,才能有所顿悟.话不多说,这是我对HTTP ...
- 蓝桥杯-无穷分数-java
/* (程序头部注释开始) * 程序的版权和版本声明部分 * Copyright (c) 2016, 广州科技贸易职业学院信息工程系学生 * All rights reserved. * 文件名称: ...
- hust1010 kmp
There is a string A. The length of A is less than 1,000,000. I rewrite it again and again. Then I go ...
- innobackup全备与恢复
前提:xtrabackup.mysql安装完成,建立测试库reading.测试表test,并插入三条数据. 1.全备: innobackupex --user=root --password ...
- poj 1001 分析
1) n = 0; return 1: 2) n = 1; bool standardizeNumNoDot(string &s){标准化是一定要得} _将‘.’前后的〇全部去除,正常retu ...
- 学习笔记:javascript 表单对象(form)
Form 对象属性 属性 描述 acceptCharset 服务器可接受的字符集. action 设置或返回表单的 action 属性. enctype 设置或返回表单用来编码内容的 MIME 类型. ...
- Arcengine 二次开发添加右键菜单
最近在搞arcengine 二次开发,遇到了好多问题,也通过网上查资料试着慢慢解决了,把解决的步骤记录下来,有需要帮助的可以看一下,也欢迎各位来批评指正. 想给自己的map application在图 ...
- OpenStack Newton版本Ceph集成部署记录
2017年2月,OpenStack Ocata版本正式release,就此记录上一版本 Newton 结合Ceph Jewel版的部署实践.宿主机操作系统为CentOS 7.2 . 初级版: 192. ...
- Maven学习-优化和重构POM
在一个复杂的项目中,项目的各个模块存在各种相互依赖关系.优化一个多模块项目的POM最好通过几步来做.总的来说,我们总是寻找一个POM中的重复或者多个兄弟POM中的重复.在多模块项目中依赖重复的模式主要 ...