-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdfs.c
More file actions
62 lines (48 loc) · 1.02 KB
/
dfs.c
File metadata and controls
62 lines (48 loc) · 1.02 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
#include <stdio.h>
#include<stdbool.h>
#define MAX 100
int st[MAX];
int top = -1;
int adj[MAX][MAX];
bool visited[MAX];
void push(int data){
st[++top] = data;
}
int pop(){
return st[top--];
}
bool isEmpty(){
return top == -1;
}
void dfs(int nodes,int start){
push(start);
while(!isEmpty()){
int u = pop();
if(!visited[u]){
visited[u] = true;
printf("%d, ", u);
for(int v = nodes; v >= 1; v--){
if(adj[u][v] && !visited[v]){
push(v);
}
}
}
}
}
int main() {
int nodes, edges;
scanf("%d%d", &nodes, &edges);
int u, v;
for(int i=0; i<MAX; i++){
for(int j=0; j<MAX; j++){
adj[i][j] = 0;
}
}
for(int i=0; i<edges; i++){
scanf("%d %d", &u, &v);
adj[u][v] = 1;
adj[v][u] = 1;
}
dfs(nodes, 1);
return 0;
}