-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathBFSshortpath.cpp
More file actions
57 lines (48 loc) · 1010 Bytes
/
Copy pathBFSshortpath.cpp
File metadata and controls
57 lines (48 loc) · 1010 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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#include<iostream>
#include<bits/stdc++.h>
using namespace std;
void BFS(int v, map<int,set<int>> adj){
map<int,bool> visit;
map<int,int> parent;
int s=1;
int t=8;
queue<int> q;
q.push(s);
visit[s]=1;
parent[s]=-1;
while(!q.empty()){
int frontnode=q.front();
q.pop();
for(auto it: adj[frontnode]){
if(!visit[it]){
visit[it]=1;
parent[it]=frontnode;
q.push(it);
}
}
}
vector<int> ans;
int currentnode = t;
ans.push_back(t);
while(currentnode!=s){
currentnode = parent[currentnode];
ans.push_back(currentnode);
}
reverse(ans.begin(),ans.end());
for(int i:ans){
cout<<i<<",";
}
}
int main(){
int n,m;
cin>>n>>m;
map<int, set<int>> adj;
for(int i=0;i<m;i++){
int u,v;
cin>>u>>v;
adj[u].insert(v);
adj[v].insert(u);
}
BFS(n, adj);
return 0;
}