Breadth-first search
From Wikipedia, the free encyclopedia
In graph theory, breadth-first search (BFS) is a graph search algorithm that begins at the root node and explores all the neighboring nodes. Then for each of those nearest nodes, it explores their unexplored neighbor nodes, and so on, until it finds the goal.
How it worksBFS is an uninformed search method that aims to expand and examine all nodes of a graph systematically in search of a solution. In other words, it exhaustively searches the entire graph without considering the goal until it finds it. It does not use a heuristic. From the standpoint of the algorithm, all child nodes obtained by expanding a node are added to a FIFO queue. In typical implementations, nodes that have not yet been examined for their neighbors are placed in some container (such as a queue or linked list) called "open" and then once examined are placed in the container "closed".
Algorithm (informal)
Note: Using a stack instead of a queue to store the nodes yet to be visited would turn this algorithm into a Depth-first search. C implementationAlgorithm of Breadth-first search: <source lang="c">
void BFS(VLink G[], int v) {
int w;
VISIT(v); /*visit vertex v*/
visited[v] = 1; /*mark v as visited : 1 */
ADDQ(Q,v);
while(!EMPTYQ(Q)) {
v = DELQ(Q); /*Dequeue v*/
w = FIRSTADJ(G,v); /*Find first neighbor, return -1 if no neighbor*/
while(w != -1) {
if(visited[w] == 0) {
VISIT(w); /*visit vertex v*/
ADDQ(Q,w); /*Enqueue current visited vertext w*/
visited[w] = 1; /*mark w as visited*/
}
w = NEXTADJ(G,v); /*Find next neighbor, return -1 if no neighbor*/
}
}
}
</source> Main Algorithm of apply Breadth-first search to graph G=(V,E): <source lang="c">
void TRAVEL_BFS(VLink G[], int visited[], int n) {
int i;
for(i = 0; i < n; i ++) {
visited[i] = 0; /* Mark initial value as 0 */
}
for(i = 0; i < n; i ++)
if(visited[i] == 0)
BFS(G,i);
}
</source> C++ implementationThis is the implementation of the above informal algorithm, where the "so-far-unexamined" is handled by the parent array. For actual C++ applications, see the Boost Graph Library.
<source lang="c"> struct Vertex {
...
std::vector<int> out;
...
};
</source>
<source lang="c"> std::vector<Vertex> graph(vertices); </source>
<source lang="c">
bool BFS(const std::vector<Vertex>& graph, int start, int end) {
std::queue<int> next;
std::map<int,int> parent;
parent[start] = -1;
next.push(start);
while (!next.empty()) {
int u = next.front();
next.pop();
// Here is the point where you can examine the u th vertex of graph
// For example:
if (u == end) return true;
for (std::vector<int>::const_iterator j = graph[u].out.begin(); j != graph[u].out.end(); ++j) {
// Look through neighbors.
int v = *j;
if (parent.count(v) == 0) {
// If v is unvisited.
parent[v] = u;
next.push(v);
}
}
}
return false;
}
</source>
Features
Space ComplexitySince all of the nodes of a level must be saved until their child nodes in the next level have been generated, the space complexity is proportional to the number of nodes at the deepest level. Given a branching factor Failed to parse (Missing texvc executable; please see math/README to configure.): b and graph depth Failed to parse (Missing texvc executable; please see math/README to configure.): d the asymptotic space complexity is the number of nodes at the deepest level, Failed to parse (Missing texvc executable; please see math/README to configure.): O(b^d) . When the number of vertices and edges in the graph are known ahead of time, the space complexity can also be expressed as Failed to parse (Missing texvc executable; please see math/README to configure.): O(|E|+|V|) where Failed to parse (Missing texvc executable; please see math/README to configure.): |E| is the cardinality of the set of edges (the number of edges), and Failed to parse (Missing texvc executable; please see math/README to configure.): |V| is the cardinality of the set of vertices. In the worst case the graph has a depth of 1 and all vertices must be stored. Since it is exponential in the depth of the graph, breadth-first search is often impractical for large problems on systems with bounded space. Time ComplexitySince in the worst case breadth-first search has to consider all paths to all possible nodes the time complexity of breadth-first search is Failed to parse (Missing texvc executable; please see math/README to configure.): b+b^2+b^3+...+b^d which asymptotically approaches Failed to parse (Missing texvc executable; please see math/README to configure.): O(b^d) . The time complexity can also be expressed as Failed to parse (Missing texvc executable; please see math/README to configure.): O(|E|+|V|) since every vertex and every edge will be explored in the worst case. CompletenessBreadth-first search is complete. This means that if there is a solution breadth-first search will find it regardless of the kind of graph. However, if the graph is infinite and there is no solution breadth-first search will diverge. OptimalityFor unit-step cost, breadth-first search is optimal. In general breadth-first search is not optimal since it always returns the result with the fewest edges between the start node and the goal node. If the graph is a weighted graph, and therefore has costs associated with each step, a goal next to the start does not have to be the cheapest goal available. This problem is solved by improving breadth-first search to uniform-cost search which considers the path costs. Nevertheless, if the graph is not weighted, and therefore all step costs are equal, breadth-first search will find the nearest and the best solution. Applications of BFSBreadth-first search can be used to solve many problems in graph theory, for example:
Finding connected ComponentsThe set of nodes reached by a BFS are the largest connected component containing the start node. Testing bipartitenessBFS can be used to test bipartiteness, by starting the search at any vertex and giving alternating labels to the vertices visited during the search. That is, give label 0 to the starting vertex, 1 to all its neighbours, 0 to those neighbours' neighbours, and so on. If at any step a vertex has (visited) neighbours with the same label as itself, then the graph is not bipartite. If the search ends without such a situation occurring, then the graph is bipartite. LiteratureKnuth, Donald E. (1997), The Art Of Computer Programming Vol 1. 3rd ed., Boston: Addison-Wesley, ISBN 0-201-89683-4, <http://www-cs-faculty.stanford.edu/~knuth/taocp.html>de:Breitensuche es:Búsqueda en anchura fr:Algorithme de parcours en largeur he:אלגוריתם חיפוש לרוחב lt:Paieška į plotį ja:幅優先探索 pl:Przeszukiwanie wszerz pt:Busca em largura ru:Поиск в ширину uk:Пошук в ширину |



