File tree Expand file tree Collapse file tree 1 file changed +35
-0
lines changed
23 - Graph Data Structure Problems/11 - Shortest Path in Undirected Graph Expand file tree Collapse file tree 1 file changed +35
-0
lines changed Original file line number Diff line number Diff line change 1+ class Solution {
2+ public:
3+ vector<int > shortestPath (vector<vector<int >>& edges, int N, int M, int src) {
4+ vector<vector<int >> adj (N);
5+ for (int i = 0 ; i < M; i++) {
6+ int u = edges[i][0 ];
7+ int v = edges[i][1 ];
8+ adj[u].push_back (v);
9+ adj[v].push_back (u);
10+ }
11+
12+ vector<int > distance (N, -1 );
13+ vector<bool > visited (N, false );
14+ queue<int > q;
15+
16+ distance[src] = 0 ;
17+ visited[src] = true ;
18+ q.push (src);
19+
20+ while (!q.empty ()) {
21+ int node = q.front ();
22+ q.pop ();
23+
24+ for (int neighbor : adj[node]) {
25+ if (!visited[neighbor]) {
26+ visited[neighbor] = true ;
27+ distance[neighbor] = distance[node] + 1 ;
28+ q.push (neighbor);
29+ }
30+ }
31+ }
32+
33+ return distance;
34+ }
35+ };
You can’t perform that action at this time.
0 commit comments