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.