// do a BFS traversal from source // // source = the source for the BFS traversal // nodes = list of all nodes from G // adj[node] = the adjacency list of node // example: adj[node] = {..., neigh, ...} => edge (node, neigh) BFS(source, G=(nodes, adj)) { // STEP 0: initialize results // d[node] = distance from source to node // p[node] = parent of node in the BFS traversal started from source // [optional] color[node] = white/gray/black // * white = not yet visited // * gray = visit in progress // * black = visited foreach (node in nodes) { d[node] = +oo; // distance not yet computed p(node) = null; // parent not yet found // [optional] color[node] = white; } // STEP 1: initialize a queue q = {} // STEP 2: add the source(s) into q d[source] = 0; // distance from source to source p[source] = null; // the source never has a parent (because it's the root of the traversal) q.push(source); // [optional] color[source] = gray; // STEP 3: start traversal using the node(s) from q while (!q.empty()) { // while still have nodes to explore // STEP 3.1: extract the next node from queue node = q.pop(); // [optional] STEP 3.2: print/use the node // STEP 3.3: expand/visit the node foreach (neigh in adj[node]) { // for each neighbour if (d[node] + 1 < d[neigh]) { // a smaller distance <=> color[neigh] == white d[neigh] = d[node] + 1; // update distance p[neigh] = node; // save parent q.push(neigh); // add neigh to the queue of nodes to be visited // [optional] color[neigh] = gray; } } // [optional] color[node] = black; } }