#include #include #include #include using namespace std; int n, m, used[1001]; vector a[1001]; void in() { scanf("%d %d", &n, &m); for (int i = 0; i < m; i++) { int v1, v2; scanf("%d %d", &v1, &v2); a[v1 - 1].push_back(v2 - 1); a[v2 - 1].push_back(v1 - 1); } } void bfs(int i) { queue q; int br1 = 1, br2 = 0, level = 0; //br1 holds the remaining number of vertices from the current level and in br2 we count the number of vertices in the next level. used[i] = 1; q.push(i); printf("level %d:", level); while (!q.empty()) { if (br1 == 0) { br1 = br2; br2 = 0; level++; printf("\nlevel %d:", level); } int g = q.front(); q.pop(); br1--; printf(" %d", g + 1); int s = a[g].size(); for (int j = 0; j < s; j++) if (used[a[g][j]] == 0) { used[a[g][j]] = 1; q.push(a[g][j]); br2++; } } printf("\n"); } /*void bfs(int i) //Here we use one queue which elements are of type pair - the first value in the pair is vertex and the second value in the pair is the level of that vertex. We use more memory here. { queue > q; int lastLevel = 0; used[i] = 1; q.push(make_pair(i, 0)); printf("level %d:", q.front().second); while (!q.empty()) { pair g = q.front(); q.pop(); if (g.second == lastLevel) printf(" %d", g.first + 1); else { lastLevel = g.second; printf("\nlevel %d: %d", g.second, g.first + 1); } int s = a[g.first].size(); for (int j = 0; j < s; j++) if (used[a[g.first][j]] == 0) { used[a[g.first][j]] = 1; q.push(make_pair(a[g.first][j], g.second + 1)); } } printf("\n"); }*/ int main() { in(); bfs(0); return 0; }