Easy Java Solution using Queue and List


  • 0
    T
    /*
        Queue to store food, List to store body.
        Only three cases to consider in move();
    */
    class SnakeGame {
    
        int x = 0, y = 0;
        int width;
        int height;
        Queue<int[]> Food = new LinkedList<>();
        List<int[]> body = new LinkedList<>();
    
        int score = 0;
        boolean hasFood;
    
        public SnakeGame(int width, int height, int[][] food) {
            this.width = width;
            this.height = height;
            this.hasFood = food.length==0;
            for(int[] foood: food) Food.add(foood);
        }
    
        /** 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[] dir = new int[2];
            int newX = x, newY = y;
            if(direction.equals("U")) newX--;
            else if(direction.equals("D")) newX++;
            else if(direction.equals("L")) newY--;
            else if(direction.equals("R")) newY++;
    
            //Case 1: out of boundary
            if(newX<0||newX>=height||newY<0||newY>=width) return -1;
            else {
                int[] food = Food.peek();
                //Case 2: eat food, keep tail and add head
                if(!Food.isEmpty()&&food[0]==newX && food[1]==newY){
                    score++;
                    Food.poll();
                    body.add(new int[]{x,y});
                    x = newX; y = newY;
                }
                //Case 3: normal move, add head, remove tail: check if hits body
                else {
                    body.add(new int[]{x,y});
                    if(!body.isEmpty()) body.remove(0);
                    for(int[] pos:body)
                        if(pos[0]==newX&&pos[1]==newY) return -1;
                    x = newX; y = newY;
                }
                return score;
            }
        }
    }
    

Log in to reply
 

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