MCPcopy Index your code
hub / github.com/neetcode-gh/leetcode / openLock

Method openLock

java/0752-open-the-lock.java:2–34  ·  view source on GitHub ↗
(String[] deadends, String target)

Source from the content-addressed store, hash-verified

1class Solution {
2 public int openLock(String[] deadends, String target) {
3 Set<String> visited = new HashSet<>();
4 for (String deadend : deadends) {
5 if (deadend.equals("0000")) {
6 return -1;
7 }
8 visited.add(deadend);
9 }
10
11 Queue<String> queue = new LinkedList<>();
12 queue.offer("0000");
13 visited.add("0000");
14
15 int turns = 0;
16 while (!queue.isEmpty()) {
17 int size = queue.size();
18 for (int i = 0; i < size; i++) {
19 String lock = queue.poll();
20 if (lock.equals(target)) {
21 return turns;
22 }
23 List<String> children = generateChildren(lock);
24 for (String child : children) {
25 if (!visited.contains(child)) {
26 visited.add(child);
27 queue.offer(child);
28 }
29 }
30 }
31 turns++;
32 }
33 return -1;
34 }
35
36 private List<String> generateChildren(String lock) {
37 List<String> children = new ArrayList<>();

Callers

nothing calls this directly

Calls 6

generateChildrenMethod · 0.95
equalsMethod · 0.80
addMethod · 0.45
isEmptyMethod · 0.45
sizeMethod · 0.45
containsMethod · 0.45

Tested by

no test coverage detected