-
Notifications
You must be signed in to change notification settings - Fork 0
/
Shortest_Path_In_Undirected_Graph.cpp
79 lines (69 loc) · 1.75 KB
/
Shortest_Path_In_Undirected_Graph.cpp
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
//{ Driver Code Starts
// Initial Template for C++
#include <bits/stdc++.h>
using namespace std;
// } Driver Code Ends
// User function Template for C++
class Solution {
public:
vector<int> shortestPath(vector<vector<int>>& edges, int N,int M, int src){
vector<int> adj[N];
for(auto it : edges)
{
adj[it[0]].push_back(it[1]);
adj[it[1]].push_back(it[0]);
}
int dist[N];
for(int i = 0; i < N; i++) dist[i] = 1e9;
dist[src] = 0;
queue<int>q;
q.push(src);
while(!q.empty())
{
int node = q.front();
q.pop();
for(auto it : adj[node])
{
if(dist[node] + 1 < dist[it])
{
dist[it] = 1 + dist[node];
q.push(it);
}
}
}
vector<int> ans(N, -1);
for(int i = 0; i < N; i++)
{
if(dist[i] != 1e9)
{
ans[i] = dist[i];
}
}
return ans;
}
};
//{ Driver Code Starts.
int main() {
int t;
cin >> t;
while (t--) {
int n, m; cin >> n >> m;
vector<vector<int>> edges;
for (int i = 0; i < m; ++i) {
vector<int> temp;
for(int j=0; j<2; ++j){
int x; cin>>x;
temp.push_back(x);
}
edges.push_back(temp);
}
int src; cin >> src;
Solution obj;
vector<int> res = obj.shortestPath(edges, n, m, src);
for (auto x : res){
cout<<x<<" ";
}
cout << "\n";
}
}
// } Driver Code Ends