Simple java using List Beats 98.42%


  • 0

    List is easy to record snake's body by shifting to right
    If eating food in this move, just add new position at end of List;
    else, remove the first element and check whether the new head in list.

    class SnakeGame {
        int[][] food;
        List<Integer> snakeBody;
        int m, n;
        int f;
        /** 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) {
            m = height;
            n = width;
            f = 0;
            snakeBody = new ArrayList<>();
            snakeBody.add(0);
            this.food = food;
        }
        
        /** 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 dx = 0, dy = 0;
            switch (direction) {
                case "U" : dx = -1; dy = 0;
                    break;
                case "L" : dx = 0; dy = -1;
                    break;
                case "R" : dx = 0; dy = 1;
                    break;
                case "D" : dx = 1; dy = 0;
                    break;
            }
            int index = snakeBody.get(snakeBody.size() - 1);
            int nx = index / n + dx;
            int ny = index % n + dy;
            if (nx < 0 || nx >= m || ny < 0 || ny >= n) return -1;
            if (f < food.length && nx == food[f][0] && ny == food[f][1]) {
                f++;
                snakeBody.add(nx * n + ny);
                return f;
            } else {
                snakeBody.remove(0);
                if (snakeBody.contains(nx * n + ny)) {
                    return -1;
                }
                snakeBody.add(nx * n + ny);
                return f;
            }
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.