-
Notifications
You must be signed in to change notification settings - Fork 0
/
leaf nodes using dfs.cpp
73 lines (67 loc) · 1.34 KB
/
leaf nodes using dfs.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
65
66
67
68
69
70
71
72
73
#include<bits/stdc++.h>
#define ll long long int
using namespace std;
int main()
{
int n;
int e;
cin>>n>>e;
int a[n+1][n+1];
stack<int>q;
bool visited[n+1];
for(int i=1; i<=n; i++)
{
for(int j=1; j<=n; j++)
{
a[i][j]=0;
}
}
while(e--)
{
int f,s;
cin>>f>>s;
a[f][s]=1;
a[s][f]=1;
}
for(int i=1; i<=n; i++)
{
visited[i]=false;
}
q.push(1);
while(!q.empty())
{
int x=q.top();
if(visited[x]==false){
//cout<<x<<endl;
visited[x]=true;
}
bool flag=true;
bool sag=true;
int lol=0;
for(int i=1; i<=n; i++)
{
if(i==x)
{
continue;
}
if(a[x][i]==1)
{
lol++;
if(visited[i])
{
continue;
}
//cout<<"here is node = "<<i<<endl;
q.push(i);
flag=false;
sag=false;
break;
}
}
if(sag==true and lol==1){
cout<<x<<endl;
}
if(flag)q.pop();
}
return 0;
}