2059.cpp (1247B)
1 class Solution { 2 public: 3 int minimumOperations(const vector<int> &nums, int start, int goal) const { 4 bool seen[1001] = {0}; 5 queue<int> q; 6 7 seen[start] = true; 8 q.emplace(start); 9 10 for (int lvl = 1; !q.empty(); lvl++) { 11 for (int l = size(q); l > 0; l--) { 12 const int crnt = q.front(); 13 q.pop(); 14 15 for (const int n : nums) { 16 const int x = crnt ^ n; 17 if (x == goal) return lvl; 18 if (x >= 0 && x <= 1000 && !seen[x]) { 19 seen[x] = true; 20 q.emplace(x); 21 } 22 23 const int y = crnt + n; 24 if (y == goal) return lvl; 25 if (y >= 0 && y <= 1000 && !seen[y]) { 26 seen[y] = true; 27 q.emplace(y); 28 } 29 30 const int z = crnt - n; 31 if (z == goal) return lvl; 32 if (z >= 0 && z <= 1000 && !seen[z]) { 33 seen[z] = true; 34 q.emplace(z); 35 } 36 } 37 } 38 } 39 40 return -1; 41 } 42 };