-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGRAPH.c
61 lines (61 loc) · 1.38 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
#include <stdio.h>
#include <stdlib.h>
int a[20][20],q[20],visited[20],reach[20],n,f=0,r=-1,count=0;
void bfs(int v)
{
int i;
for(i=1;i<=n;i++)
if(a[v][i]&&!visited[i])
{
visited[i]=1;
q[++r]=i;
}
if(f<=r)
bfs(q[f++]);
}
void dfs(int v)
{
int i;
reach[v]=1;
for(i=1;i<=n;i++)
if(a[v][i]&&!reach[i])
{
printf("%d->%d\n",v,i);
count++;
dfs(i);
}
}
int main()
{
int v,ch,i,j;
printf("\nenter no. of vertices:");
scanf("%d",&n);
for(i=1;i<=n;i++)
reach[i]=visited[i]=q[i]=0;
printf("\nEnter graph data in matrix form:\n");
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
scanf("%d",&a[i][j]);
printf("\n1.BFS\n2.DFS\n3.Exit\nEnter choice:");
scanf("%d",&ch);
switch(ch)
{
case 1:printf("\nEnter vertex:");
scanf("%d",&v);
bfs(v);
printf("\nThe nodes that are reacheble from %d are:\n",v);
for(i=1;i<=n;i++)
if(visited[i])
printf("%d ",i);
break;
case 2:dfs(1);
if(count==n-1)
printf("\ngraph is connected");
else
printf("\ngraph is not connected");
break;
case 3:exit(0);
default:printf("\nInvalid choice");
}
return 0;
}