- Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy path_1971.java
48 lines (45 loc) · 1.67 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
packagecom.fishercoder.solutions.secondthousand;
importjava.util.HashMap;
importjava.util.HashSet;
importjava.util.LinkedList;
importjava.util.Map;
importjava.util.Queue;
importjava.util.Set;
publicclass_1971 {
publicstaticclassSolution1 {
publicbooleanvalidPath(intn, int[][] edges, intstart, intend) {
if (start == end) {
returntrue;
}
Map<Integer, Set<Integer>> neighborsMap = newHashMap<>();
for (int[] edge : edges) {
intu = edge[0];
intv = edge[1];
Set<Integer> neighbors1 = neighborsMap.getOrDefault(u, newHashSet<>());
neighbors1.add(v);
neighborsMap.put(u, neighbors1);
Set<Integer> neighbors2 = neighborsMap.getOrDefault(v, newHashSet<>());
neighbors2.add(u);
neighborsMap.put(v, neighbors2);
}
Queue<Integer> queue = newLinkedList<>();
Set<Integer> visitedVertices = newHashSet<>();
queue.offer(start);
while (!queue.isEmpty()) {
intsize = queue.size();
for (inti = 0; i < size; i++) {
Integercurr = queue.poll();
for (intneighbor : neighborsMap.getOrDefault(curr, newHashSet<>())) {
if (neighbor == end) {
returntrue;
}
if (visitedVertices.add(neighbor)) {
queue.offer(neighbor);
}
}
}
}
returnfalse;
}
}
}