Skip to content

Commit f719891

Browse files
authored
Create main.cpp
1 parent 6dd4ac6 commit f719891

File tree

1 file changed

+35
-0
lines changed
  • 23 - Graph Data Structure Problems/11 - Shortest Path in Undirected Graph

1 file changed

+35
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
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+
};

0 commit comments

Comments
 (0)