Simple Java LinkedList Solution


  • 0
    I
    public class SnakeGame {
    
        private LinkedList<Integer[]> q;
        private int w, h;
        private int[][] food;
        
        /** 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.w = width;
            this.h = height;
            this.q = new LinkedList<Integer[]>();
            this.food = food;
            
            q.offer(new Integer[]{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 dir) {
            int y = q.peekFirst()[0], x = q.peekFirst()[1];
            switch(dir) {
                case "U": {
                    y--;
                    break;
                }
                case "D": {
                    y++;
                    break;
                }
                case "R": {
                    x++;
                    break;
                }
                default: {
                    x--;
                    break;
                }
            }
            
            if(x < 0 || x >= w || y < 0 || y >= h) {
                return -1;
            }
            
            
            int currFood = q.size() - 1;
            if(currFood < food.length && y == food[currFood][0] && x == food[currFood][1]) {
                q.offerFirst(new Integer[]{y, x});
                return q.size() - 1;
            }
            
            int count = 0;
            for(Integer[] c : q) {
                count++;
                if(c[0] == y && c[1] == x && count != q.size()) {
                    return -1;
                }
            }
            
            q.offerFirst(new Integer[]{y, x});
            q.pollLast();
            return q.size() - 1;
        }
    }
    
    /**
     * 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.