My Java Solution (Easy to Understand)


  • 0
    C

    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]. */
        int width;
        int height;
        int[][] food;
        int length;
        List<int[]> list;
        int x;
        int y;
        int k;
    public SnakeGame(int width, int height, int[][] food) {
        this.width = width;
        this.height = height;
        this.food = food;
        length = 0;
        list = new ArrayList<int[]> ();
        x = 0;
        y = 0;
        k = 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) {
        if (direction.equals("U")) {
            if (x - 1 < 0) {
                return -1;
            }
            x = x - 1;
        } else if (direction.equals("L")) {
            if (y - 1 < 0) {
                return -1;
            }
            y = y - 1;
        } else if (direction.equals("R")) {
            if (y + 1 >= width) {
                return -1;
            }
            y = y + 1;
        } else if (direction.equals("D")) {
            if (x + 1 >= height) {
                return -1;
            }
            x = x + 1;
        } else {
            return -1;
        }
        
        int[] pos = {x, y};
        for (int i = 1; i < list.size(); i ++) {
        // do not need to check the first position, since it will be empty soon
            if (list.get(i)[0] == x && list.get(i)[1] == y) {
                return -1;
            }
        }
        if (k < food.length && food[k][0] == x && food[k][1] == y) {
        // will reach a fruit and increase the length in next step
            length ++;
            k ++;
        } else if (list.size() > 0) {
        // otherwise, just move one step forward
            list.remove(0);
        }
        list.add(pos);
        return length;
    }
    

    }


Log in to reply
 

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