-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsq4-A.cpp
More file actions
86 lines (78 loc) · 1.2 KB
/
Copy pathsq4-A.cpp
File metadata and controls
86 lines (78 loc) · 1.2 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
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
74
75
76
77
78
79
80
81
82
83
84
85
86
/* Graph */
#include <bits/stdc++.h>
using namespace std;
typedef struct node
{
int v;
struct node *next;
}node;
node *graph[10];
int *visited;
int n;
void bfs(int);
void dfs(int);
int main()
{
freopen("in", "r", stdin);
freopen("out", "w", stdout);
int n1, e;
cin>>n1>>e;
n = n1;
visited = (int *)malloc(n*sizeof(int));
for(int i=0; i<n; i++) visited[i] = 0;
for(int i=0; i<n; i++) graph[i] = NULL;
while(e--)
{
int u, v;
cin>>u>>v;
node *ptr = (node *)malloc(sizeof(node)), *tmp;
tmp = graph[u];
ptr->v = v;
ptr->next = NULL;
if(tmp==NULL) graph[u] = ptr;
else
{
while(tmp->next!=NULL) tmp = tmp->next;
tmp->next = ptr;
}
}
cout<<"\n\nBFS:\n\n\n";
bfs(0);
for(int i=0; i<n; i++) visited[i] = 0;
cout<<"\n\nDFS:\n\n\n";
dfs(0);
return 0;
}
void bfs(int u)
{
queue<int> q;
q.push(u);
visited[u] = 1;
while(!q.empty())
{
u = q.front();
cout<<u<<endl;
q.pop();
node *ptr = graph[u];
while(ptr!=NULL)
{
if(!visited[ptr->v])
{
q.push(ptr->v);
visited[ptr->v] = 1;
}
ptr = ptr->next;
}
}
}
void dfs(int u)
{
visited[u] = 1;
cout<<u<<endl;
node *ptr = graph[u];
while(ptr!=NULL)
{
if(!visited[ptr->v]) dfs(ptr->v);
ptr = ptr->next;
}
}