# 广度优先遍历(BFS)
先访问一个顶点所有相邻的顶点,然后再依次访问每个顶点的相邻的顶点,以此类推,最终访问到所有的顶点。
比如,从 0 开始先访问周围顶点:
![](https://img.kancloud.cn/03/8c/038cacb06a28a9aea62eeb9f4a491f7a_510x458.png)
再到隔一层的点:
![](https://img.kancloud.cn/28/c2/28c20cc147f3c815753817df8c940275_534x472.png)
然后再隔一层:
![](https://img.kancloud.cn/de/4d/de4dd340ebb87c0062c09370153057b2_522x454.png)
# 代码实现
使用 `队列` 不断重放:
![](https://img.kancloud.cn/86/7e/867e56c9bd1a061bf579e676adba8eae_702x1360.png)
~~~
let Colors = {
WHITE: 0,
GREY: 1,
BLACK: 2
};
let initializeColor = vertices => {
let color = {};
vertices.forEach(v => color[v] = Colors.WHITE);
return color;
};
let breadthFirstSearch = (graph, startVertex, callback) => {
let vertices = graph.getVertices();
let adjList = graph.getAdjList();
let color = initializeColor(vertices);
let queue = new Queue();
queue.enqueue(startVertex);
while (!queue.isEmpty()) {
let u = queue.dequeue();
adjList.get(u).forEach(n => {
if (color[n] === Colors.WHITE) {
color[n] = Colors.GREY;
queue.enqueue(n);
}
});
color[u] = Colors.BLACK;
if (callback) callback(u);
}
};
~~~