Easy Java Solution 201 ms


  • 0
    H
    public class SnakeGame {
    
        /** 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]. */
        //cell represents snake body 
        public class Cell{
            int x;
            int y;
            Cell next;
            public Cell(int x, int y){
                this.x = x;
                this.y = y;
            }
        }
        private int w;
        private int h;
        private int[][] food;
        private int currf;      //number of foods eaten at current time
        private Cell head;
        public SnakeGame(int width, int height, int[][] food) {
            w = width;
            h = height;
            this.food = food;
            currf = 0;
            head = new Cell(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) {
            int currx = head.x;
            int curry = head.y;
            if (direction.equals("U")) {
            	currx--;
            } else if (direction.equals("D")) {
            	currx++;
            } else if (direction.equals("L")) {
            	curry--;
            } else if (direction.equals("R")) {
            	curry++;
            } else {
            	return -1;
            }
            if (currx < 0 || currx >= h || curry < 0 || curry >= w) return -1;
            Cell newh = new Cell(currx, curry);
            newh.next = head;
            head = newh;
            //loop current eaten food number times
            for (int i = 0; i < currf; i++) {
                newh = newh.next;
                if (newh.x == head.x && newh.y == head.y) {
                    return -1;
                }
            }
            //if reach food, increment currf and return
            if (currf < food.length && head.x == food[currf][0] && head.y == food[currf][1]) {
                return ++currf;
            } else { // else remove the tail
                newh.next = null;
                return currf;
            }
        }
    }
    

Log in to reply
 

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