-
Notifications
You must be signed in to change notification settings - Fork 1
/
graph.c
79 lines (74 loc) · 1.21 KB
/
graph.c
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
#include <stdio.h>
#define size 4
#define max 10
int visited[size];
int stack[max];
int queue[max];
int top=-1,front=-1,rear=-1;
int ar[size][size];
void dfs(int i);
void bfs(int i);
void main()
{
printf("ENTER THE MATRIX");
printf("\n");
for(int i=0;i<size;i++)
{
for(int j=0;j<size;j++)
{
scanf("%d",&ar[i][j]);
}
}
for(int i=0;i<size;i++)
visited[i]=0;
dfs(0);
for(int i=0;i<size;i++)
visited[i]=0;
bfs(0);
}
void dfs(int i)
{
stack[++top]=i;
int x;
printf("The DFS RESULT IS: ");
while(top>=0)
{
x=stack[top--];
if(visited[x]==0)
{
printf("%d ",x);
visited[x]=1;
for(int j=0;j<size;j++)
{
if(ar[x][j]==1)
stack[++top]=j;
}
}
}
}
void bfs(int i)
{
printf("\n\n");
printf("THE BFS RESULT IS: %d ",i);
visited[i]=1;
queue[++rear]=i;
front++;
int x;
while(front<size)
{
x=queue[front];
front++;
for(int j=0;j<size;j++)
{
if(ar[x][j]==1)
{
if (visited[j]==0)
{
printf("%d ",j);
queue[++rear]=j;
visited[j]=1;
}
}
}
}
}