353.Design Snake Game

Solution :HashSet + Deque

class SnakeGame {
    int score;
    int width;
    int height;
    Deque<Integer> snake;
    Set<Integer> bodySet;
    int[][] food;
    int foodIndex;
    /** 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) {
        this.width = width;
        this.height = height;
        this.food = food;
        this.foodIndex = 0;
        this.score = 0;
        snake = new LinkedList<>();
        snake.offerLast(0);
        bodySet = new HashSet<>();
        bodySet.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 currentHead = snake.peekFirst();
        int newHeadX = currentHead / width;
        int newHeadY = currentHead % width;
        switch(direction){
            case "U":
                newHeadX--;
                break;
            case "L":
                newHeadY--;
                break;
            case "R":
                newHeadY++;
                break;
            case "D":
                newHeadX++;
                break; 
        }

        //Game Over-Out of bound
        if( newHeadX<0 || newHeadX>=height || newHeadY<0 || newHeadY>=width){
            return -1;
        }
        //Game Over-Eating body.
        int newHeadVal = newHeadX * width + newHeadY;
        bodySet.remove(snake.peekLast());
        if(bodySet.contains(newHeadVal)){
            return -1;
        }

        //Move
        bodySet.add(newHeadVal);
        snake.offerFirst(newHeadVal);

        if(foodIndex < food.length && newHeadX == food[foodIndex][0] && newHeadY == food[foodIndex][1]){
            bodySet.add(snake.peekLast());
            foodIndex++;
            return ++score;
        }
        else{
            snake.pollLast();
            return score;
        }
    }
}

/**
 * Your SnakeGame object will be instantiated and called as such:
 * SnakeGame obj = new SnakeGame(width, height, food);
 * int param_1 = obj.move(direction);
 */

results matching ""

    No results matching ""