Skip to content

Commit 112b16c

Browse files
committed
Time: 45 ms (13.98%), Space: 14.4 MB (97.88%) - LeetHub
1 parent d99ba4f commit 112b16c

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
# define RED 0
2+
# define BLUE 1
3+
class Solution {
4+
int dist[2][105];
5+
public:
6+
Solution(){
7+
memset(dist, -1, sizeof(dist));
8+
}
9+
10+
void bfs(int src, vector<pair<int, int>> adj[]) {
11+
queue<pair<int,int>> q;
12+
q.push({src, RED});
13+
q.push({src, BLUE});
14+
dist[RED][src] = 0;
15+
dist[BLUE][src] = 0;
16+
17+
while(!q.empty()){
18+
auto curr = q.front(); q.pop();
19+
int v = curr.first;
20+
int color_prev = curr.second;
21+
22+
for(auto u: adj[v]){
23+
if(u.second == !color_prev){
24+
int to = u.first;
25+
int to_color = u.second;
26+
if(dist[to_color][to] == -1){
27+
dist[to_color][to] = dist[color_prev][v] + 1;
28+
q.push({to, to_color});
29+
}
30+
}
31+
}
32+
}
33+
}
34+
35+
vector<int> shortestAlternatingPaths(int n, vector<vector<int>>& red_edges, vector<vector<int>>& blue_edges) {
36+
vector<pair<int, int>> adj[n];
37+
for(auto& r: red_edges){
38+
adj[r[0]].push_back({r[1], RED});
39+
}
40+
41+
for(auto& b: blue_edges){
42+
adj[b[0]].push_back({b[1], BLUE});
43+
}
44+
45+
bfs(0, adj);
46+
vector<int> ans(n);
47+
for (int i = 0; i < n; ++i){
48+
cout << dist[RED][i] << " " << dist[BLUE][i] << endl;
49+
ans[i] = min(dist[RED][i] == -1 ? INT_MAX : dist[RED][i], dist[BLUE][i] == -1 ? INT_MAX : dist[BLUE][i]);
50+
if(ans[i] == INT_MAX)
51+
ans[i] = -1;
52+
}
53+
54+
return ans;
55+
}
56+
};

0 commit comments

Comments
 (0)