0% found this document useful (0 votes)
6 views

BFS_Shortest_Reach_In_A_Graph.cpp

Uploaded by

dotienloc2005
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

BFS_Shortest_Reach_In_A_Graph.cpp

Uploaded by

dotienloc2005
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

#include <cmath>

#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <queue>
using namespace std;

class Graph {
public:
int n;
vector<pair<int, int>> edges;
vector<vector<int>> adj;
Graph(int n) {
this->n = n;
adj.resize(n + 1);
}

void add_edge(int u, int v) {


edges.push_back({u,v});
}

vector<int> shortest_reach(int start) {


for (auto node : edges) {
int u = node.first;
int v = node.second;
adj[u].push_back(v);
adj[v].push_back(u);
}

vector<int> dist(n+1, -1);


queue<int> q;
q.push(start);
dist[start] = 0;
while (!q.empty()) {
int node = q.front();
q.pop();

for (auto edge : adj[node]) {


if (dist[edge] == -1) {
dist[edge] = dist[node] + 6;
q.push(edge);
}
}
}
return dist;
}
};

int main() {
int queries;
cin >> queries;

for (int t = 0; t < queries; t++) {


int n, m;
cin >> n;
// Create a graph of size n where each edge weight is 6:
Graph graph(n);
cin >> m;
// read and set edges
for (int i = 0; i < m; i++) {
int u, v;
cin >> u >> v;
// add each edge to the graph
graph.add_edge(u, v);
}
int startId;
cin >> startId;
// Find shortest reach from node s
vector<int> distances = graph.shortest_reach(startId);

for (int i = 1; i < distances.size(); i++) {


if (i != startId) {
cout << distances[i] << " ";
}
}
cout << endl;
}

return 0;
}

You might also like