Thursday, August 11, 2016

LeetCode [353] Design Snake Game

Design a Snake game that is played on a device with screen size = width x heightPlay the game online if you are not familiar with the game.
The snake is initially positioned at the top left corner (0,0) with length = 1 unit.
You are given a list of food's positions in row-column order. When a snake eats the food, its length and the game's score both increase by 1.
Each food appears one by one on the screen. For example, the second food will not appear until the first food was eaten by the snake.
When a food does appear on the screen, it is guaranteed that it will not appear on a block occupied by the snake.
Example:
Given width = 3, height = 2, and food = [[1,2],[0,1]].

Snake snake = new Snake(width, height, food);

Initially the snake appears at position (0,0) and the food at (1,2).

|S| | |
| | |F|

snake.move("R"); -> Returns 0

| |S| |
| | |F|

snake.move("D"); -> Returns 0

| | | |
| |S|F|

snake.move("R"); -> Returns 1 (Snake eats the first food and right after that, the second food appears at (0,1) )

| |F| |
| |S|S|

snake.move("U"); -> Returns 1

| |F|S|
| | |S|

snake.move("L"); -> Returns 2 (Snake eats the second food)

| |S|S|
| | |S|

snake.move("U"); -> Returns -1 (Game over because snake collides with border)
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
class SnakeGame
{
    set<pair<int, int>> hist;    //keep the coordinates of the current snake. used to decide if the snake eats itself
    deque<pair<int, int>> snake; //also keep the snake coordinates. used to update the snake body after each movement
    vector<vector<int>> food;
    int pos; //store the food position
    int w, h;

  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)
    {
        w = width;
        h = height;
        pos = 0;
        this->food = food;
        pair<int, int> p = make_pair(0, 0);
        snake.push_front(p);
        hist.insert(p);
    }

    /** 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)
    {
        pair<int, int> tail = snake.back();
        pair<int, int> head = snake.front();

        //remove the tail
        snake.pop_back();
        hist.erase(tail);

        if (direction == "U")
            head.first--;
        if (direction == "L")
            head.second--;
        if (direction == "R")
            head.second++;
        if (direction == "D")
            head.first++;

        //game over
        if (head.first < 0 || head.first >= h || head.second < 0 || head.second >= w || hist.count(head))
            return -1;

        //add new head
        snake.push_front(head);
        hist.insert(head);

        //no more food. score is the snake size minus the original size 1
        if (pos == food.size())
            return snake.size() - 1;

        //extend the snake body by adding the tail back
        if (head.first == food[pos][0] && head.second == food[pos][1])
        {
            snake.push_back(tail);
            hist.insert(tail);
            pos++;
        }

        return snake.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);
 */
class SnakeGame {
    int foodIndex = 0;
    Set<Integer> hist = new HashSet<>();
    Deque<Integer> body = new LinkedList<>();
    int w, h;
    int[][] food;

    /** 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]. */
    public SnakeGame(int width, int height, int[][] food) {
        w = width;
        h = height;
        this.food = food;
        body.add(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. */
    public int move(String direction) {
        int head = body.peekFirst();
        int tail = body.peekLast();

        //remove tail
        body.removeLast();
        hist.remove(tail);

        int i = head/w, j = head%w;
        if(direction.equals("U")) i--;
        if(direction.equals("D")) i++;
        if(direction.equals("L")) j--;
        if(direction.equals("R")) j++;
        int newPostion = i*w+j;

        //game over
        if(i<0 || i>=h || j<0 || j>=w || hist.contains(newPostion)) return -1;

        //add new head
        body.addFirst(newPostion);
        hist.add(newPostion);

        //no more food, score is body size -1
        if(foodIndex == food.length) return body.size()-1;

        //eat food, body length increases by 1 to the end
        if(i==food[foodIndex][0] && j==food[foodIndex][1]){
            body.add(tail);
            hist.add(tail);
            foodIndex++;
        }

        return body.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);
 */

No comments:

Post a Comment