forked from rituparna-ui/hacktorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathshortestPathUndirectedGraph.cpp
More file actions
48 lines (46 loc) · 969 Bytes
/
shortestPathUndirectedGraph.cpp
File metadata and controls
48 lines (46 loc) · 969 Bytes
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
//BFS
#include <bits/stdc++.h>
using namespace std;
vector<int> BFS(int n, int src, vector<int> adj[])
{
vector<int> Dist(n, INT_MAX);
queue<int> q;
q.push(src);
Dist[src] = 0;
while (!q.empty())
{
int node = q.front();
q.pop();
for (auto it : adj[node])
{
if (Dist[it] > 1 + Dist[node])
{
Dist[it] = 1 + Dist[node];
q.push(it);
}
}
}
return Dist;
}
int main()
{
int n, m;
cin >> n >> m;
vector<int> adj[n];
for (int i = 0; i < m; i++)
{
int u, v;
cin >> u >> v;
adj[u].push_back(v);
adj[v].push_back(u);
}
int src;
cout << "Enter Source\n";
cin >> src;
vector<int> res = BFS(n, src, adj);
cout << "Shortest Distances of various Nodes from the source are:\n";
for (int i = 0; i < n; i++)
{
cout << i << "->" << res[i] << endl;
}
}