-
Notifications
You must be signed in to change notification settings - Fork 28
Expand file tree
/
Copy path1129. Shortest Path with Alternating Colors
More file actions
37 lines (34 loc) · 1.14 KB
/
1129. Shortest Path with Alternating Colors
File metadata and controls
37 lines (34 loc) · 1.14 KB
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
37
class Solution {
public int[] shortestAlternatingPaths(int n, int[][] redEdges, int[][] blueEdges) {
List[] adj = new ArrayList[n];
for(int i=0;i<n;i++){
adj[i] = new ArrayList<>();
}
for(int[] red:redEdges){
adj[red[0]].add(new int[]{red[1],0});
}
for(int[] blue:blueEdges){
adj[blue[0]].add(new int[]{blue[1],1});
}
Queue<int[]> queue = new LinkedList<>();
int[] res = new int[n];
Arrays.fill(res,-1);
res[0]=0;
boolean[][] v = new boolean[n][2];
queue.add(new int[]{0,0,-1}); //currentPos,distance,color
while(queue.size()>0){
int[] prev = queue.remove();
List<int[]> nodes = adj[prev[0]];
for(int[] next:nodes){
if(!v[next[0]][next[1]] && next[1]!=prev[2]){
if(res[next[0]]==-1){
res[next[0]]=prev[1] + 1;
}
v[next[0]][next[1]] = true;
queue.add(new int[]{next[0],prev[1]+1,next[1]});
}
}
}
return res;
}
}