I've started learning graphs theory and was doing a question from Hackerrank https://www.hackerrank.com/challenges/bfsshortreach/problem, which is basically asking to perform a BFS, mark all elements in same level as 6*level and mark all un-reachable nodes as -1. I tried it the following way, I get a seg fault while creating my adjList, am I accessing the input vector<vector<int>> edges
in a wrong way? or is it something else.
This is my 2-3 bfs code, so I also wanted to know if my implementation is okay, and is it doing what it's supposed to be doing or am I off? (I know the question asks for ans vector
to be 1-n
not order of visited like it is currently, maybe I could use a map, or a histogram, or a pair with original value and sort it with second later or something, haven't figured that part out) Thank you.
Code:
vector<vector<int>> Graph(vector<vector<int>>& edges) {
vector<vector<int>> ans;
for(auto i: edges) {
ans[i[0]].push_back(i[1]);
ans[i[1]].push_back(i[0]);
} return ans;
}
vector<int> bfs(int n, int m, vector<vector<int>>& edges, int s) { // no. of vertex, no. of edges, edges, start
vector<vector<int>> adjList;
// adjList.resize(n);
adjList = Graph(edges);
vector<int> ans(n + 1);
vector<bool> visited(n + 1);
queue<int> q;
visited[s] = true;
q.push(s);
int i = 0;
while(!q.empty()) {
int temp = q.front(); q.pop();
// int len = q.size();
for(int j: adjList[temp]) {
if(!visited[j]) {
ans.push_back(6*i);
visited[j] = true;
q.push(j);
}
} i++;
}
for(int i = 1; i <= n; i++) if(i % 6 != 0 && i != s) ans[i] = -1;
ans.erase(ans.begin() + s);
return ans;
}
Tested on
int main() {
vector<vector<int>> edges = {{1, 2}, {1, 3} };
vector<int> som = bfs(4, 2, edges, 1);
return 0;
}