-
Notifications
You must be signed in to change notification settings - Fork 0
/
dfs_stack.cpp
64 lines (55 loc) · 1 KB
/
dfs_stack.cpp
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
58
59
60
61
62
63
64
#include<bits/stdc++.h>
using namespace std;
const int N =1e5+10;
vector<int>g[N];
bool vis[N];
int dis[N];
stack<int>Q;
int main()
{
int n,m;
cin>>n>>m;
for(int i=0; i<m; i++)
{
int u,v;
cin>>u>>v;
g[u].push_back(v); // directed graph
//g[y].push_back(x);
}
//cout<<"Source node :" ;
//int source; cin>>source;
Q.push(0);
vis[0]=1;
dis[0]=0;
vector<int>order;
while(!Q.empty())
{
int node=Q.top();
Q.pop();
order.push_back(node);
for(int adj : g[node])
{
if(vis[adj]) continue;
vis[adj] = 1;
dis[adj] =dis[node] + 1;
Q.push(adj);
}
}
cout<<"order :\t" ;
for(int v : order) cout<< v <<" ";
cout<<endl;
for(int node=0; node<n; node++)
cout<<"node : "<<node<<"\t"<<"distance : "<<dis[node]<<endl;
}
/*
9 9
0 2
0 3
0 1
1 7
7 8
2 4
3 4
4 5
5 6
*/