-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathshortestPathUnweightedUndirectedGraph.cpp
More file actions
62 lines (58 loc) · 1.09 KB
/
Copy pathshortestPathUnweightedUndirectedGraph.cpp
File metadata and controls
62 lines (58 loc) · 1.09 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
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
// TC -> O[N+E]
// Sc => O[N]+O[N]
vector<int> shortestPathUnweightedUndirectedGraph(vector<int> adj[], int V, int src)
{
vector<int> shortestDist(V, INT_MAX);
queue<int> q;
shortestDist[src] = 0;
q.push(src);
while (!q.empty())
{
int node = q.front();
q.pop();
for (auto it : adj[node])
{
if (shortestDist[it] > shortestDist[node] + 1)
{
shortestDist[it] = shortestDist[node] + 1;
q.push(it);
}
}
}
return shortestDist;
}
};
// { Driver Code Starts.
int main()
{
int tc;
cin >> tc;
while (tc--)
{
int V, E;
cout << "Enter number of vertices and edges: " << endl;
cin >> V >> E;
vector<int> adj[V];
for (int i = 0; i < E; i++)
{
int u, v;
cin >> u >> v;
adj[u].push_back(v);
adj[v].push_back(u);
}
int src;
cout << "Enter Source node: " << endl;
cin >> src;
Solution obj;
vector<int> ans = obj.shortestPathUnweightedUndirectedGraph(adj, V, src);
for (int x : ans)
cout << x << " ";
cout << endl;
}
return 0;
} // } Driver Code Ends