forked from himanshu010/dsa-programming-codes
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgeneric graph hashmap.cpp
More file actions
132 lines (119 loc) · 2.66 KB
/
Copy pathgeneric graph hashmap.cpp
File metadata and controls
132 lines (119 loc) · 2.66 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
#include <bits/stdc++.h>
using namespace std;
#define int long long int
#define ld long double
#define F first
#define S second
#define P pair<int, int>
#define pb push_back
#define mkp make_pair
template <typename T> class Graph
{
map<T, list<T>> adjList;
public:
Graph()
{
}
void addEdge(T u, T v, bool bidir)
{
adjList[u].push_back(v);
if (bidir)
{
adjList[v].push_back(u);
}
}
void print()
{
for (auto i : adjList)
{
cout << i.F << " ---> ";
for (auto entry : i.S)
{
cout << entry << ",";
}
cout << endl;
}
}
void bfs(T src)
{
queue<T> q;
map<T, bool> visited;
q.push(src);
visited[src] = 1;
while (!q.empty())
{
T node = q.front();
cout << node << " ";
q.pop();
// for neighbour of current node
for (auto neighbour : adjList[node])
{
if (!visited[neighbour])
{
q.push(neighbour);
visited[neighbour] = 1;
}
}
}
}
void sssp(T src)
{
queue<T> q;
map<T, int> dist;
map<T, T> parent;
int ans;
for (auto i : adjList)
{
dist[i.F] = MAX;
}
q.push(src);
dist[src] = 0;
parent[src] = src;
while (!q.empty())
{
T node = q.front();
q.pop();
// for neighbour of current node
for (auto neighbour : adjList[node])
{
if (dist[neighbour] == INT_MAX)
{
q.push(neighbour);
dist[neighbour] = dist[node] + 1;
parent[neighbour] = node;
}
}
}
// Print the distance to all node
for (auto i : adjList)
{
T node = i.first;
cout << "Dist of " << node << " is " << dist[node] << endl;
}
}
};
int32_t main()
{
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
// int t;cin>>t;while(t--)
{
int i, j, k, n, m, ans = 0, cnt = 0, sum = 0;
Graph<int> g;
cin >> n;
for (int i = 0; i < n; ++i)
{
int l, r;
bool bidir;
cin >> l >> r >> bidir;
g.addEdge(l, r, bidir);
}
g.print();
g.bfs(0);
}
}