Here is the algorithm to see the connectivity of 2 nodes in a graph using BFS.
To see how the graph is constructed see : http://iwriteanything.blogspot.in/2017/01/represent-graph-adjacency-list-using.html
int connected (int a, int b, vector<vector<int>> & v) {
queue<int> q;
vector<int> v1(v.size(), 0);
for (int i = 0; i< v[a].size(); i++) {
q.push(v[a][i]);
}
v1[a] = 1;
while(!q.empty()) {
if (q.front() == b) return 1;
if (v1[q.front()] == 0) {
for (int i = 0; i< v[q.front()].size(); i++) {
q.push(v[q.front()][i]);
}
}
v1[q.front()] = 1;
q.pop();
}
return 0;
}
No comments:
Post a Comment