The vector<int> bfs
is local to the method bfs_of_graph then how can we return the vector as it would be erased in the memory and only garbage values should be printed in the calling method. But I find the values are present. How ?
class Solution {
public:
vector<int> bfs_of_graph(int no_of_nodes, vector<int> adj_list[]) {
queue<int> qt;
vector<int> bfs;
vector<int> visited(no_of_nodes + 1, 0);
for (int i = 1; i <= no_of_nodes; ++i) {
// Node in graph not visited
if (visited[i] == 0) {
qt.push(i);
visited[i] = 1;
while (!qt.empty()) {
int node = qt.front();
qt.pop();
bfs.push_back(node);
for (auto ele: adj_list[node]) {
if (visited[ele] == 0) {
qt.push(ele);
visited[ele] = 1;
}
}
}
}
}
return bfs;
}
};