-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path01BFS.cpp
More file actions
71 lines (66 loc) · 1.49 KB
/
01BFS.cpp
File metadata and controls
71 lines (66 loc) · 1.49 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
#include <iostream>
#include <vector>
#include <deque>
#include <climits>
using namespace std;
vector<pair<int,int>> adjList[100005];
int dist[100005];
void print(int n)
{
for(int i=1; i<=n; i++)
{
cout << i << "-> ";
for(auto neighbour : adjList[i])
{
cout << "(" << neighbour.first << " with weight " << neighbour.second << ") ";
}
cout << endl;
}
}
void bfs(int src, int n)
{
deque<int> q;
q.push_back(src);
for(int i=1; i<=n; i++)
{
dist[i] = INT_MAX;
}
dist[src] = 0;
while(!q.empty())
{
int node = q.front(); q.pop_front();
for(auto neighbour : adjList[node])
{
if(dist[node] + neighbour.second < dist[neighbour.first])
{
dist[neighbour.first] = dist[node] + neighbour.second;
if(neighbour.second==0)
{
q.push_front(neighbour.first);
}
else
{
q.push_back(neighbour.first);
}
}
}
}
for(int i=1; i<=n; i++)
{
cout << "Distance of " << i << " is " << dist[i] << endl;
}
}
int main() {
int n, e;
cin >> n >> e;
for(int i=0; i<e; i++)
{
int u, v, weight;
cin >> u >> v >> weight;
adjList[u].emplace_back(make_pair(v,weight));
adjList[v].emplace_back(make_pair(u,weight));
}
bfs(1,n);
print(n);
return 0;
}