We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
while (querySize--) {
int n, m;
cin >> n >> m;
vector<list<int>> graph(n + 1);
vector<int> visited(n + 1, 0);
vector<int> store(n + 1, -1);
for (int i = 0; i < m; i++) {
int u, v;
cin >> u >> v;
graph[u].push_back(v);
graph[v].push_back(u);
}
int s;
cin >> s;
queue<int> q;
q.push(s);
visited[s] = 1;
store[s] = 0;
while (!q.empty()) {
int k = q.front();
q.pop();
for (auto adj : graph[k]) {
if (!visited[adj]) {
visited[adj] = 1;
store[adj] = store[k] + 6;
q.push(adj);
}
}
}
// Output without trailing space
bool first = true;
for (int i = 1; i <= n; i++) {
if (i == s) continue;
if (!first) cout << " ";
cout << store[i];
first = false;
}
cout << endl;
}
return 0;
}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
BFS: Shortest Reach
You are viewing a single comment's thread. Return to all comments →
C++ code:
include
include
include
include
using namespace std;
int main() { int querySize; cin >> querySize;
}