forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathshortest-path-with-alternating-colors.cpp
36 lines (35 loc) · 1.25 KB
/
shortest-path-with-alternating-colors.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
// Time: O(n + e), e is the number of red and blue edges
// Space: O(n + e)
class Solution {
public:
vector<int> shortestAlternatingPaths(int n, vector<vector<int>>& red_edges, vector<vector<int>>& blue_edges) {
vector<vector<unordered_set<int>>> neighbors(n, vector<unordered_set<int>>(2));
for (const auto& edge : red_edges) {
neighbors[edge[0]][0].emplace(edge[1]);
}
for (const auto& edge : blue_edges) {
neighbors[edge[0]][1].emplace(edge[1]);
}
const auto& INF = max(2 * n - 3, 0) + 1;
vector<vector<int>> dist(n, vector<int>(2, INF));
dist[0] = {0, 0};
queue<pair<int, int>> q({{0, 0}, {0, 1}});
while (!q.empty()) {
int i, c;
tie(i, c) = q.front(); q.pop();
for (const auto& j : neighbors[i][c]) {
if (dist[j][c] != INF) {
continue;
}
dist[j][c] = dist[i][1 ^ c] + 1;
q.emplace(j, 1 ^ c);
}
}
vector<int> result;
for (const auto& d : dist) {
const auto& x = *min_element(d.cbegin(), d.cend());
result.emplace_back((x != INF) ? x : -1);
}
return result;
}
};