Java easy to understand Deque Solution with comments


  • 0
    A
    public class SnakeGame {
        int h = 0;
        int w = 0;
        Deque<Integer> snake;
        List<Integer> foods;
        int eat = 0;//how many food has been eaten
        /** 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) {
            snake = new ArrayDeque<>();
            foods = new ArrayList<>();
            h = height;
            w = width;
            for (int i = 0; i < food.length; i++) {
                foods.add(food[i][0] * w + food[i][1]);
            }
            snake.offerLast(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 foodNext = -1;
            if (!foods.isEmpty()) foodNext = foods.get(0);
            
            int headNext = move(direction, snake.peekFirst());
            if (headNext == -1) return -1;
            if (headNext == foodNext) {
                snake.offerFirst(foodNext);
                foods.remove(0);
                eat++;
            } else {
                snake.pollLast();
                snake.offerFirst(headNext);
            }
            return eat;
        }
        
        private int move(String d, int pos) {
            int x = pos / w;
            int y = pos % w;
            if (d.equals("U")) {
                x -= 1;
            } else if (d.equals("D")) {
                x += 1;
            } else if (d.equals("L")) {
                y -= 1;
            } else {
                y += 1;
            }
            if (x < 0 || x >= h
                || y < 0 || y >= w) return -1;//collide with borders
            int ret = x * w + y;
            if (snake.contains(ret) && (snake.peekLast() != ret)) return -1;//collide with snake itself
            return ret;
        }
    }
    
    /**
     * Your SnakeGame object will be instantiated and called as such:
     * SnakeGame obj = new SnakeGame(width, height, food);
     * int param_1 = obj.move(direction);
     */
    

Log in to reply
 

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