Skip to content

Commit c1a9aa2

Browse files
committed
Time: 7 ms (46.49%), Space: 43.4 MB (18.82%) - LeetHub
1 parent c63f7d1 commit c1a9aa2

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
class Solution {
2+
public int[] shortestAlternatingPaths(int n, int[][] redEdges, int[][] blueEdges) {
3+
HashMap<Integer,Set<Pair<Integer,Integer>>> graph = new HashMap<>();// Here use set instead of array list is to prevent duplicate edges in same label
4+
Queue<Pair<Integer,Integer>> queue = new LinkedList<>();
5+
Set<Pair<Integer,Integer>> visited = new HashSet<>();
6+
int[] res = new int[n];
7+
Arrays.fill(res,-1);
8+
res[0] = 0;
9+
10+
for(int i=0;i<n;i++)
11+
{
12+
graph.put(i,new HashSet<>());
13+
}
14+
15+
for(int[] redEdge:redEdges)
16+
{
17+
graph.get(redEdge[0]).add(new Pair<>(redEdge[1],1));
18+
}
19+
for(int[] blueEdge:blueEdges)
20+
{
21+
graph.get(blueEdge[0]).add(new Pair<>(blueEdge[1],2));
22+
}
23+
24+
int dis = 0;
25+
queue.add(new Pair<>(0,-1));
26+
while(!queue.isEmpty())
27+
{
28+
int size = queue.size();
29+
for(int i=0;i<size;i++)
30+
{
31+
Pair<Integer,Integer> curPair = queue.poll();
32+
int curNode = curPair.getKey();
33+
int curLabel = curPair.getValue();
34+
Set<Pair<Integer,Integer>> setPair = graph.get(curNode);
35+
for(Pair<Integer,Integer> adjPair:setPair)
36+
{
37+
int adjNode = adjPair.getKey();
38+
int adjLabel = adjPair.getValue();
39+
40+
if(visited.contains(adjPair)||curLabel==adjLabel)
41+
continue;
42+
43+
if(res[adjNode]==-1)
44+
res[adjNode] = dis+1;
45+
visited.add(adjPair);
46+
queue.add(adjPair);
47+
}
48+
}
49+
dis++;
50+
}
51+
52+
return res;
53+
}
54+
}

0 commit comments

Comments
 (0)