class Solution { public: int openLock(vector<string>& deadends, string target) { queue<string> q; unordered_set<string> visited(deadends.begin(), deadends.end()); if (visited.find("0000") != visited.end()) return -1; q.push("0000"); visited.insert("0000"); int qLength = q.size(); int nextQ = 0; int rank = 0; while (!q.empty()) { string res = q.front(); q.pop(); qLength--; if (res == target) return rank; for (int i = 0; i < 4; i++) { string temp = res; temp[i] = ((temp[i] - '0' + 1) % 10) + '0'; if (visited.find(temp) == visited.end()) { visited.insert(temp); q.push(temp); nextQ++; } temp = res; temp[i] = ((temp[i] - '0' - 1 + 10) % 10) + '0'; // Handle wraparound if (visited.find(temp) == visited.end()) { visited.insert(temp); q.push(temp); nextQ++; } } if (qLength <= 0) { qLength = nextQ; nextQ = 0; rank++; } } return -1; } };
from collections import deque class Solution: def openLock(self, deadends, target): q = deque(["0000"]) visited = set(deadends) if "0000" in visited: return -1 visited.add("0000") rank = 0 while q: qLength = len(q) for _ in range(qLength): res = q.popleft() if res == target: return rank for i in range(4): for move in (-1, 1): temp = list(res) temp[i] = str((int(temp[i]) + move) % 10) temp = ''.join(temp) if temp not in visited: visited.add(temp) q.append(temp) rank += 1 return -1