forked from akshitagit/CPP
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbfs.cpp
More file actions
38 lines (32 loc) · 764 Bytes
/
Copy pathbfs.cpp
File metadata and controls
38 lines (32 loc) · 764 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
vector<int> Graph::bfs(int node){
vector<int> prev(numOfNodes+1,-1);
visited.resize(numOfNodes+1,false);
queue<int> q;
q.push(node);
visited[node]=true;
while(!q.empty()){
node = q.front(); q.pop();
for(int child:G[node]){
if(!visited[child]){
q.push(child);
visited[child]=true;
prev[child]=node;
}
}
}
return prev;
}
//To get the path from StartingNode to lastNode
vector<int> Graph::reconstructPathFromBFS(
vector<int> prev, int startingNode, int endingNode){
vector<int> path; //To store the path
int ind=endingNode;
path.push_back(endingNode);
while(prev[ind]!=-1){
path.push_back(prev[ind]);
ind = prev[ind];
}
reverse(path.begin(), path.end());
if(path[0]==startingNode) return path;
else return {-1};
}