广度优先搜索(Breadth First Research,BFS)
类比二叉树的层序遍历
void BFS(Vertex V)
{
visited[V]=true;
Enqueue(V,Q);
while(!IsEmpty(Q))
{
V=Dequeue(Q);
for (V的每个邻接点W)
if (!Visited[W])
{
visited[W]=true;
Enqueue(W,Q);
}
}
}
- 若有N个顶点、E条边,时间复杂度是
- 邻接表存储,有O(N+E)
- 邻接矩阵存储,有O(N^2)