AIZU ONLINE JUDGE Aizu - ALDS1_11_C Breadth First Search Solution
Problem Link : https://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ALDS1_11_C
Solution in C++:
///La ilaha illellahu muhammadur rasulullah
///******Bismillahir-Rahmanir-Rahim******///
///Abul Hasnat Tonmoy
///Department of CSE,23rd batch
///Islamic University,Bangladesh
///**********ALLAH IS ALMIGHTY************///
#include <bits/stdc++.h>
using namespace std;
const int N = 109;
int vis[N];
int dis[N];
vector<int> vec[N];
int source, nod = 0;
queue<int> q;
void bfs(int s) {
vis[s] = 1;
dis[s] = 0;
q.push(s);
while (!q.empty()) {
nod = q.front();
q.pop();
for (int i = 0; i < vec[nod].size(); i++) {
int next = vec[nod][i];
if (vis[next] == 0) {
vis[next] = 1;
dis[next] = dis[nod] + 1;
q.push(next);
}
}
}
}
int main() {
int n;
cin >> n;
for (int i = 0; i < n; i++) {
int u, k;
cin >> u >> k;
for (int j = 0; j < k; j++) {
int v;
cin >> v;
vec[u].push_back(v);
}
}
bfs(1);
for (int i = 1; i <= n; i++) {
if (i > 1 && !dis[i]) dis[i] = -1;
cout << i << " " << dis[i] << endl;
}
}
No comments