-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathImplementation.cpp
More file actions
46 lines (41 loc) · 1.06 KB
/
Copy pathImplementation.cpp
File metadata and controls
46 lines (41 loc) · 1.06 KB
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
39
40
41
42
43
44
45
46
//implementation of BFS
#include<bits/stdc++.h>
using namespace std;
vector<vector<int>> adjList;
int nodes;
vector<int> d,p;
vector<bool> vis;
void BFS(int source){
queue<int> q;
vector<bool> visited(nodes,false);
vector<int> distanceFromSource(nodes,-1), parent(nodes);
/*
if -1 then it's not connected with the graph component that
contains source, because path length cannot be negative in BFS
*/
q.push(source);
visited[source]=true;
parent[source]=-1;
distanceFromSource[source]=0;
while(!q.empty()){
int v=q.front();
q.pop();
for(auto it: adjList[v]){
q.push(it);
visited[it]=true;
distanceFromSource[it]=distanceFromSource[v]+1;
parent[it]=v;
}
}
d=distanceFromSource;
p=parent;
vis=visited;
}
vector<int> pathFromSource(int source,int node){
BFS(source);
vector<int> path;
if(!vis[node]) return path;
for(int i=node; i!=-1; i=p[node]) path.push_back(i);
reverse(path.begin(),path.end());
return path;
}