File tree Expand file tree Collapse file tree 1 file changed +120
-0
lines changed Expand file tree Collapse file tree 1 file changed +120
-0
lines changed Original file line number Diff line number Diff line change
1
+ /* BFS Traversal of Graph using Adjacency List
2
+ Representation*/
3
+
4
+ #include < iostream>
5
+ using namespace std ;
6
+
7
+ struct node
8
+ {
9
+ node *next;
10
+ int vertex;
11
+ };
12
+ class graph
13
+ {
14
+ node *G[20 ];
15
+ int visited[20 ];
16
+ int n;
17
+ public:
18
+ void create ();
19
+ void insert (int ,int );
20
+ void BFS_List (int );
21
+ };
22
+ class queue
23
+ {
24
+ int data[30 ];
25
+ int r,f;
26
+ public:
27
+ queue ()
28
+ {
29
+ r=f=-1 ;
30
+ }
31
+ int empty ()
32
+ {
33
+ if (r==-1 )
34
+ return 1 ;
35
+ return 0 ;
36
+ }
37
+ void insert (int x)
38
+ {
39
+ if (empty ())
40
+ r=f=0 ;
41
+ else
42
+ r=r+1 ;
43
+ data[r]=x;
44
+ }
45
+ int Delete ()
46
+ {
47
+ int x=data[f];
48
+ if (r==f)
49
+ r=f=-1 ;
50
+ else
51
+ f=f+1 ;
52
+ return x;
53
+ }
54
+ };
55
+ void graph::create ()
56
+ {
57
+ int i,vi,vj,e,n;
58
+ cout<<" \n Enter no. of vertices:" ;
59
+ cin>>n;
60
+ for (i=1 ;i<=n;i++)
61
+ G[i]=NULL ;
62
+ visited[i]=0 ;
63
+ cout<<" \n Enter no. of edges:" ;
64
+ cin>>e;
65
+ for (i=1 ;i<=e;i++)
66
+ {
67
+ cout<<" \n Enter an edge:" ;
68
+ cin>>vi>>vj;
69
+ insert (vi,vj);
70
+ insert (vj,vi);
71
+ }
72
+ }
73
+ void graph::insert (int vi, int vj)
74
+ {
75
+ node *p,*q;
76
+ q=new node;
77
+ q->vertex =vj;
78
+ q->next =NULL ;
79
+ if (G[vi]==NULL )
80
+ {G[vi]=q;}
81
+ else
82
+ {
83
+ p=G[vi];
84
+ while (p->next !=NULL )
85
+ {
86
+ p=p->next ;
87
+ }
88
+ p->next =q;
89
+ }
90
+ }
91
+
92
+ void graph::BFS_List (int v)
93
+ {
94
+ int i,v2;
95
+ queue q;
96
+ node *p;
97
+ q.insert (v);
98
+ cout<<" \n Visit" <<v;
99
+ visited[v]=1 ;
100
+ while (!q.empty ())
101
+ {
102
+ v=q.Delete ();
103
+ for (p=G[v];p!=NULL ;p=p->next )
104
+ {
105
+ v2=p->vertex ;
106
+ if (!visited[v2])
107
+ {
108
+ q.insert (v2);
109
+ visited[v2]=1 ;
110
+ cout<<" \n visit" <<v2;
111
+ }
112
+ }
113
+ }
114
+ }
115
+ int main ()
116
+ {
117
+ graph t;
118
+ t.create ();
119
+ t.BFS_List (1 );
120
+ }
You can’t perform that action at this time.
0 commit comments