2120.cpp (857B)
1 // 2120. Execution of All Suffix Instructions Staying in a Grid 2 class Solution { 3 public: 4 vector<int> executeInstructions(int n, const vector<int> &startPos, string s) { 5 const auto valid = [n](int x, int y) { return x >= 0 && x < n && y >= 0 && y < n; }; 6 7 vector<int> res; 8 res.reserve(s.size()); 9 for (int k = 0; k < s.size(); k++) { 10 int x = startPos[0], y = startPos[1]; 11 for (int i = k; i < s.size(); i++) { 12 if (s[i] == 'L') y--; 13 if (s[i] == 'R') y++; 14 if (s[i] == 'U') x--; 15 if (s[i] == 'D') x++; 16 if (!valid(x, y)) { 17 res.push_back(i - k); 18 goto next; 19 } 20 } 21 res.push_back(s.size() - k); 22 next:; 23 } 24 return res; 25 } 26 };