有两种用于探索图的通用算法:广度优先搜索 (BFS) 和深度优先搜索 (DFS)。这些算法的诀窍是它们从未探索列表中的所有路径开始,当他们访问路径时,他们将这些路径添加到探索列表中。当您访问每个节点时,您会将其从未探索列表中删除,这样您就不会重新访问它。通过在每种情况下仅从未探索列表中拉出节点,您就不会出现双重反击的情况。
以下是带有检查以防止循环和 BFS 的 DFS 示例:
function DFS(G,v):
label v as explored
for all edges e in G.adjacentEdges(v) do
if edge e is unexplored then
w ← G.adjacentVertex(v,e)
if vertex w is unexplored then
label e as a discovery edge
recursively call DFS(G,w)
else
label e as a back edge
现在 BFS:
procedure BFS(G,v):
create a queue Q
enqueue v onto Q
mark v
while Q is not empty:
t ← Q.dequeue()
if t is what we are looking for:
return t
for all edges e in G.adjacentEdges(t) do
u ← G.adjacentVertex(t,e)
if u is not marked:
mark u
enqueue u onto Q
return none