-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathgraph.cpp
More file actions
120 lines (103 loc) · 2 KB
/
graph.cpp
File metadata and controls
120 lines (103 loc) · 2 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
#include <bits/stdc++.h>
using namespace std;
typedef pair<int, int> edgeWeightPair;
class Graph
{
int V;
list<edgeWeightPair> *adj;
public:
Graph(int V)
{
this->V = V;
adj = new list<edgeWeightPair>[V];
}
void addEdge(int u, int v, int w)
{
adj[u].push_back(make_pair(v, w));
adj[v].push_back(make_pair(u, w));
}
void printNeighbour(int chk)
{
cout << chk << ":";
for (auto i = adj[chk].begin(); i != adj[chk].end(); i++)
{
cout << " (" << (*i).first << ", " << (*i).second << ")";
}
}
void BFS(int source)
{
vector<bool>visited(V,false);
queue<int> Q;
visited[source] = true;
Q.push(source);
while (!Q.empty())
{
int u = Q.front();
cout << u << " ";
Q.pop();
for (auto element : adj[u])
{
int v = element.first;
if (visited[v] != true)
{
visited[v] = true;
Q.push(v);
}
}
}
}
void DFS(int source)
{
static vector<bool>visited(V,false);
visited[source] = true;
cout << source << " ";
for (auto element : adj[source])
{
int v = element.first;
if (visited[v] != true)
{
DFS(v);
}
}
}
};
int main()
{
int V, E, source;
cin >> V >> E >> source;
Graph g(V);
for (int i = 0; i < E; i++)
{
int u, v, w;
cin >> u >> v >> w;
g.addEdge(u, v, w);
}
for (int i = 0; i < V; i++)
{
g.printNeighbour(i);
cout << endl;
}
cout << endl
<< endl;
g.BFS(source);
cout << endl
<< endl;
g.DFS(source);
cout << endl
<< endl;
return 0;
}
/*
Bi-Directional Weighted Graph
7 10 0
0 1 7
0 2 1
0 5 3
1 3 11
2 3 3
3 6 1
6 5 2
6 4 4
5 4 6
2 5 8
*/