Problem solution · C++

Design Snake Game

Design Snake Game: a C++ solution using sliding window or two pointers. Learn the idea, check the complexity, and read the full code, with credit to walkccc LeetCode Solutions.

Technique
Sliding window or two pointers
Source
walkccc LeetCode Solutions
Length
71 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Sliding window or two pointers

For Design Snake Game, the implementation maintains a moving interval and updates only the information that enters or leaves the window.

  1. Choose the invariant that makes a window valid or useful.
  2. Advance the right boundary and add the new element.
  3. 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.

Source

Code and credit

This code comes from walkccc LeetCode Solutions by P.-Y. Chen (walkccc) and is used under the MIT licence.

Full codeDesign Snake Game · C++C++
Use this to learn the idea, then write your own version.
class SnakeGame { public:  /** Initialize your data structure here.     @param width - screen width     @param height - screen height     @param food - A list of food positions     E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the     second is at [1,0]. */  SnakeGame(int width, int height, vector<vector<int>>& food)      : width(width), height(height), food(food) {    lookup.insert(getId(0, 0));    body.push_back(getId(0, 0));  }   /** Moves the snake.      @param direction - 'U' = Up, 'L' = Left, 'R' = Right, 'D' = Down      @return The game's score after the move. Return -1 if game over.      Game over when snake crosses the screen boundary or bites its body. */  int std::move(string direction) {    // the old head's position    int i = body.front() / width;    int j = body.front() % width;     // Update the head's position and check if it's out-of-bounds.    if (direction == "U" && --i < 0)      return -1;    if (direction == "L" && --j < 0)      return -1;    if (direction == "R" && ++j == width)      return -1;    if (direction == "D" && ++i == height)      return -1;     const int newHead = getId(i, j);     // 1. Eat food and increase the size by 1.    if (k < food.size() && i == food[k][0] && j == food[k][1]) {      lookup.insert(newHead);      body.push_front(newHead);      ++k;      return ++score;    }     // 2. new head != old tail and eat body!    if (newHead != body.back() && lookup.contains(newHead))      return -1;     // 3. normal case    // Remove the old tail first, then add new head because new head may be in    // old tail's position.    lookup.erase(body.back());    lookup.insert(newHead);    body.pop_back();    body.push_front(newHead);    return score;  }  private:  int width;  int height;  int score = 0;  int k = 0;  // food's index  vector<vector<int>> food;  unordered_set<int> lookup;  deque<int> body;  // snake's body   int getId(int i, int j) {    return i * width + j;  }}; 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗