Leetcode 353 Solution

This article provides solution to leetcode question 353 (design-snake-game)

https://leetcode.com/problems/design-snake-game

Solution

class SnakeGame { queue<pair<int, int>> q; set<pair<int, int>> snake; queue<pair<int, int>> foods; int m_width; int m_height;
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<pair<int, int>> food) { m_width = width; m_height = height; q.push(make_pair(0, 0)); snake.insert(make_pair(0, 0)); for (auto pair : food) foods.push(pair); }
/** 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 move(string direction) { auto head = q.back(); auto next = head;
if (direction == "U") next.first--; else if (direction == "L") next.second--; else if (direction == "R") next.second++; else if (direction == "D") next.first++;
if (next.first < 0 || next.first >= m_height || next.second < 0 || next.second >= m_width) return -1;
if (snake.find(next) != snake.end() && next != q.front()) return -1;
if (foods.empty() == false && foods.front() == next) { snake.insert(next); q.push(next); foods.pop(); } else { snake.erase(q.front()); q.pop(); snake.insert(next); q.push(next); }
return q.size() - 1; } };
/** * Your SnakeGame object will be instantiated and called as such: * SnakeGame obj = new SnakeGame(width, height, food); * int param_1 = obj.move(direction); */