- Choose the invariant that makes a window valid or useful.
- Advance the right boundary and add the new element.
- Move the left boundary only as needed while maintaining the invariant and updating the answer.
Code notes
- 71 lines of C++ from the credited upstream file 353.cpp.
- The implementation visibly relies on sequence storage, hash lookup, work queue.
- No explicit loop blocks detected.
Complexity
Confirm that neither pointer moves backwards; if so, the scan is usually linear apart from the window’s data-structure operations.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class SnakeGame {2 public:3 /** Initialize your data structure here.4 @param width - screen width5 @param height - screen height6 @param food - A list of food positions7 E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the8 second is at [1,0]. */9 SnakeGame(int width, int height, vector<vector<int>>& food)10 : width(width), height(height), food(food) {11 lookup.insert(getId(0, 0));12 body.push_back(getId(0, 0));13 }14 15 /** Moves the snake.16 @param direction - 'U' = Up, 'L' = Left, 'R' = Right, 'D' = Down17 @return The game's score after the move. Return -1 if game over.18 Game over when snake crosses the screen boundary or bites its body. */19 int std::move(string direction) {20 21 int i = body.front() / width;22 int j = body.front() % width;23 24 25 if (direction == "U" && --i < 0)26 return -1;27 if (direction == "L" && --j < 0)28 return -1;29 if (direction == "R" && ++j == width)30 return -1;31 if (direction == "D" && ++i == height)32 return -1;33 34 const int newHead = getId(i, j);35 36 37 if (k < food.size() && i == food[k][0] && j == food[k][1]) {38 lookup.insert(newHead);39 body.push_front(newHead);40 ++k;41 return ++score;42 }43 44 45 if (newHead != body.back() && lookup.contains(newHead))46 return -1;47 48 49 50 51 lookup.erase(body.back());52 lookup.insert(newHead);53 body.pop_back();54 body.push_front(newHead);55 return score;56 }57 58 private:59 int width;60 int height;61 int score = 0;62 int k = 0; 63 vector<vector<int>> food;64 unordered_set<int> lookup;65 deque<int> body; 66 67 int getId(int i, int j) {68 return i * width + j;69 }70};71