Skip to content

Commit 463fd98

Browse files
authored
Create shortest-path-with-alternating-colors.cpp
1 parent d36187e commit 463fd98

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
// Time: O(n + e), e is the number of red and blue edges
2+
// Space: O(n + e)
3+
4+
class Solution {
5+
public:
6+
vector<int> shortestAlternatingPaths(int n, vector<vector<int>>& red_edges, vector<vector<int>>& blue_edges) {
7+
vector<vector<unordered_set<int>>> neighbors(n, vector<unordered_set<int>>(2));
8+
for (const auto& edge : red_edges) {
9+
neighbors[edge[0]][0].emplace(edge[1]);
10+
}
11+
for (const auto& edge : blue_edges) {
12+
neighbors[edge[0]][1].emplace(edge[1]);
13+
}
14+
const auto& INF = max(2 * n - 3, 0) + 1;
15+
vector<vector<int>> dist(n, vector<int>(2, INF));
16+
dist[0] = {0, 0};
17+
queue<pair<int, int>> q({{0, 0}, {0, 1}});
18+
while (!q.empty()) {
19+
int i, c;
20+
tie(i, c) = q.front(); q.pop();
21+
for (const auto& j : neighbors[i][c]) {
22+
if (dist[j][c] != INF) {
23+
continue;
24+
}
25+
dist[j][c] = dist[i][1 ^ c] + 1;
26+
q.emplace(j, 1 ^ c);
27+
}
28+
}
29+
vector<int> result;
30+
for (const auto& d : dist) {
31+
const auto& x = *min_element(d.cbegin(), d.cend());
32+
result.emplace_back((x != INF) ? x : -1);
33+
}
34+
return result;
35+
}
36+
};

0 commit comments

Comments
 (0)