Breadth-first search

About

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 #include <bits/stdc++.h> using namespace std; const int N = 1e5 + 2; bool vis[N]; vector<int> adj[N]; int main() { memset(vis, 0, sizeof(vis)); int m; cin >> m; int x, y; for (int i = 0; i < m - 1; i++) { cin >> x >> y; adj[x].push_back(y); adj[y].push_back(x); } queue<int> q; q.push(1); vis[1] = true; while (!q.empty()) { int node = q.front(); q.pop(); cout << node << " "; vector<int>::iterator it; for (it = adj[node].begin(); it != adj[node].end(); it++) { if (!vis[*it]) { vis[*it] = 1; q.push(*it); } } } return 0; }

The Breadth-first search(BFS) is an algorithm for searching a tree data structure for a node that satisfies a given property. It starts at the tree root and explores all nodes at the present depth prior to moving on to the nodes at the next depth level. Extra memory, usually a queue, is needed to keep track of the child nodes that were encountered but not yet explored. For example, in a chess endgame a chess engine may build the game tree from the current position by applying all possible moves, and use breadth-first search to find a win position for white. Implicit trees (such as game trees or other problem-solving trees) may be of infinite size; breadth-first search is guaranteed to find a solution node[1] if one exists.

Approach

A boolean visited array is used to mark the visited vertices. For simplicity, it is assumed that all vertices are reachable from the starting vertex. BFS uses a queue data structure for traversal.
  • Consider the graph you want to navigate.
  • Select any vertex in your graph (say v1), from which you want to traverse the graph.
  • Utilize the following two data structures for traversing the graph:
    • Visited array (size of the graph)
    • Queue data structure
  • Add the starting vertex to the visited array, and afterward, add v1's adjacent vertices to the queue data structure.
  • Now, using the FIFO concept:
    • Remove the first element from the queue.
    • Put the removed element into the visited array.
    • Add the adjacent vertices of the removed element to the queue.
    • Repeat these steps until the queue is not empty and no vertex is left to be visited.

Time Complexity

  • Worst Case Time Complexity is: O(V + E)
  • Average Case Time Complexity is: O(V + E)
  • Best Case Time Complexity is: Ω(1)