forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path_1971.java
49 lines (45 loc) · 1.66 KB
/
_1971.java
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
38
39
40
41
42
43
44
45
46
47
48
49
package com.fishercoder.solutions;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
public class _1971 {
public static class Solution1 {
public boolean validPath(int n, int[][] edges, int start, int end) {
if (start == end) {
return true;
}
Map<Integer, Set<Integer>> neighborsMap = new HashMap<>();
for (int[] edge : edges) {
int u = edge[0];
int v = edge[1];
Set<Integer> neighbors1 = neighborsMap.getOrDefault(u, new HashSet<>());
neighbors1.add(v);
neighborsMap.put(u, neighbors1);
Set<Integer> neighbors2 = neighborsMap.getOrDefault(v, new HashSet<>());
neighbors2.add(u);
neighborsMap.put(v, neighbors2);
}
Queue<Integer> queue = new LinkedList<>();
Set<Integer> visitedVertices = new HashSet<>();
queue.offer(start);
while (!queue.isEmpty()) {
int size = queue.size();
for (int i = 0; i < size; i++) {
Integer curr = queue.poll();
for (int neighbor : neighborsMap.getOrDefault(curr, new HashSet<>())) {
if (neighbor == end) {
return true;
}
if (visitedVertices.add(neighbor)) {
queue.offer(neighbor);
}
}
}
}
return false;
}
}
}