DFS(Dpeth-first Search)
顾名思义,就是深度搜索,一条路走到黑,再选新的路。一个例子就是说,DFS很像好奇的小孩,你给这个小孩几个盒子套盒子,好奇的小孩肯定会一个盒子打开后继续再在这个盒子里面搜索。等把这一套盒子都打开完,再打开第二套的。Wikipedia上的讲解是:“Depth-first search(DFS) is an algorithmfor traversing or searching treeor graphdata structures. One starts at the root(selecting some arbitrary node as the root in the case of a graph) and explores as far as possible along each branch before backtracking.” 通常来说简便的DFS写法是用递归,如果非递归的话就是栈套迭代,思想是一样的。
递归写法的DFS伪代码如下:
Input: A graph G and a root v of G
procedure DFS(G,v):
label v as discovered
for all edges from v to w in G.adjacentEdges(v) do
if vertex w is not labeled as discovered then
recursively call DFS(G,w)
非递归写法的DFS伪代码如下:
Input: A graph G and a root v of G
procedure DFS-iterative(G,v):
let S be a stack
S.push(v)
while S is not empty
v ← S.pop()
if v is not labeled as discovered:
label v as discovered
for all edges from v to w in G.adjacentEdges(v) do
S.push(w)
BFS(Breadth-first Search)
这个就是相对于BFS的另外一种对图的遍历方法,对于一个节点来说先把所有neighbors都检查一遍,再从第一个neighbor开始,循环往复。由于BFS的这个特质,BFS可以帮助寻找最短路径。Wikipedia上面对BFS的定义是:“In graph theory, breadth-first search(BFS) is a strategy for searching in a graphwhen search is limited to essentially two operations: (a) visit and inspect a node of a graph; (b) gain access to visit the nodes that neighbor the currently visited node. The BFS begins at a root node and inspects all the neighboring nodes. Then for each of those neighbor nodes in turn, it inspects their neighbor nodes which were unvisited, and so on. Compare BFS with the equivalent, but more memory-efficient
Iterative deepening depth-first searchand contrast with depth-first search.”
通常BFS用queue+循环实现,伪代码如下:
Input: A graph G and a root v of G
procedure BFS(G,v) is
create a queue Q
create a set V
add v to V
enqueue v onto Q
while Q is not empty loop
t ← Q.dequeue()
if t is what we are looking for then
return t
end if
for all edges e in G.adjacentEdges(t) loop
u ← G.adjacentVertex(t,e)
if u is not in V then
add u to V
enqueue u onto Q
end if
end loop
end loop
return none
end BFS