-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathgraph.cpp
More file actions
143 lines (97 loc) · 1.97 KB
/
graph.cpp
File metadata and controls
143 lines (97 loc) · 1.97 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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
//**** IMPORTANT *****//
// Implementation of Graph using C++ STL
//vector < int >v [n]
//It defines an array of vectors whose index value ranges from 0 till n-1
//It means v[0] , v[1] , …. v[n-1] all are vectors.
#include<bits/stdc++.h>
#include<iomanip>
#include<cstdio>
using namespace std;
class graph {
public:
//graph(int V);
vector<int> adj[7];
int V=7;
void edge(int u,int v);
void printGraph();
void print();
void BFS(int s);
};
/*graph::graph(int V)
{
this->V = V;
adj = new list<int>[V];
} */
void graph::edge(int u,int v)
{
adj[u].push_back(v);
adj[v].push_back(u);
}
void graph::printGraph()
{
for (int v = 1; v < V; ++v)
{
cout << "\n Adjacency list of vertex "
<< v << "\n head ";
for (auto x : adj[v])
cout << "-> " << x;
printf("\n");
}
}
void graph::print()
{
for (int v = 1; v < V; ++v)
{
cout << "\n Adjacency list of vertex "
<< v << "\n head ";
for (int x=0;x<adj[v].size();x++)
{
cout << "-> " << adj[v][x];
//printf("\n");
}
cout<<endl;
}
}
void graph::BFS(int s)
{
cout<<" Breadh First Traversal of Graph "<<endl;
bool *flag= new bool[V];
for(int i = 0; i < V; i++)
{ flag[i] = false; }
list<int> queue;
flag[s]=true;
queue.push_back(s);
//list<int> queue::iterator i;
while(!queue.empty())
{
s=queue.front();
cout<<s<<" ";
queue.pop_front();
for(int j=0;j<adj[s].size();j++)
{
if(flag[adj[s][j]]==false)
{
queue.push_back(adj[s][j]);
flag[adj[s][j]]=true;
}
}
}
}
int main()
{
//No of Vertcies
graph g;
//g(5);
g.edge( 1, 2);
g.edge( 1, 3);
g.edge( 2, 4);
g.edge( 2, 5);
g.edge( 3, 5);
g.edge( 4, 6);
g.edge( 5, 6);
g.printGraph();
cout<<endl;
g.BFS(1);
// cout<<a[1][2];
g.print();
}