BFS (Breadth First Search)
Starting from a distinguished source vertex, BFS will traverse the graph 'breadth first'. That is, BFS will visit vertices that are direct neighbors of the source vertex (first layer), neighbors of direct neighbors (second layer), and so on, layer by layer.
Idea of Implementation:
BFS will start with the insertion of the source vertex s into a queue, then processes the queue as follows: take out the front most vertex u from the queue, enqueue all unvisited neighbors of u and mark them as visited. With the help of queue, BFS will visit and all vertices in the connected component that contains s layer by layer.
import java.util.*;
public class Graph2 {
private int V; //Number of vertices
private LinkedList<Integer> adj[]; //adjacency list; array of LinkedList
public Graph2(int v) {
V = v;
adj = new LinkedList[v];
for (int i = 0; i < v; i++) {
adj[i] = new LinkedList<>();
}
}
public void addEdge(int v, int w) {
adj[v].add(w);
}
//BFS start with a source
public void BFS(int s) {
boolean visited[] = new boolean[V];
LinkedList<Integer> queue = new LinkedList<Integer>();
visited[s] = true;
queue.add(s);
while (queue.size() != 0) {
s = queue.poll();
System.out.println(s + " ");
Iterator<Integer> i = adj[s].listIterator();
while (i.hasNext()) {
int n = i.next();
if (!visited[n]) {
visited[n] = true;
queue.add(n);
}
}
}
}
public static void main(String args[]) {
Graph2 g = new Graph2(4);
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 2);
g.addEdge(2, 0);
g.addEdge(2, 3);
g.addEdge(3, 3);
g.BFS(2); //2 0 3 1
}
}
Visualization: like an ink in the middle of water, dispersing from the center until making the entire water dark
Application: 用BFS求最短路(迷宫问题)