yokostan / Leetcode-Solutions

Doing exercise on Leetcode. Carry on!
0 stars 3 forks source link

Leetcode #353. Design Snake Game #273

Open yokostan opened 5 years ago

yokostan commented 5 years ago
class SnakeGame {

    class Point {
        int x;
        int y;
        Point(int x, int y) {
            this.x = x;
            this.y = y;
        }
        public boolean isEqual(Point p) {
            return this.x == p.x && this.y == p.y;
        }
    }

    int[][] food;
    int rows, cols;
    int len;
    Point cur;
    LinkedList<Point> snake;

    /** 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.food = food;
        this.rows = height;
        this.cols = width;

        len = 0;
        snake = new LinkedList<Point>();
        snake.add(new Point(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. */
    public int move(String direction) {
        Point newHead = new Point(snake.get(0).x, snake.get(0).y);

        if (direction.equals("U")) {
            newHead.x--;
        }else if (direction.equals("D")) {
            newHead.x++;
        }else if (direction.equals("L")) {
            newHead.y--;
        }else if (direction.equals("R")){
            newHead.y++;
        }

        if (newHead.x < 0 || newHead.x >= rows || newHead.y < 0 || newHead.y >= cols) return -1;

        for (int i = 1; i < snake.size() - 1; i++) {
            Point next = snake.get(i);
            if (next.isEqual(newHead)) return -1;
        }

        snake.addFirst(newHead);

        if (len < food.length) {
            Point p = new Point(food[len][0], food[len][1]);
            if (newHead.isEqual(p)) len++;
        }

        while (snake.size() > len + 1) snake.removeLast();

        return len;
    }
}

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