My Java Solution Using Wrapper Class to Represent Position


  • 0
    int width, height, row = 0, col = 0, score = 0, index = 0;
    int[][] food;
    LinkedList<Position> snakeList = new LinkedList<>();
    Set<Position> snakeSet = new HashSet<>();
    
    public SnakeGame(int width, int height, int[][] food) {
        this.width = width;
        this.height = height;
        this.food = food;
        Position tmp = new Position(0, 0);
        snakeList.addFirst(tmp);
        snakeSet.add(tmp);
    }
    
    public int move(String direction) {
        Position removed = snakeList.removeLast();
        snakeSet.remove(removed);
        
        if(direction.equals("U")) row--;
        else if(direction.equals("L")) col--;
        else if(direction.equals("R")) col++;
        else row++;
        Position tmp = new Position(row, col);
    
        if(row < 0 || col < 0 || row >= height || col >= width || snakeSet.contains(tmp)) return -1;
        snakeList.addFirst(tmp);
        snakeSet.add(tmp);
        if(score < food.length && food[index][0] == row && food[index][1] == col) {
            score++;
            index++;
            snakeList.addLast(removed);
            snakeSet.add(removed);
        }
        return score;
    }
    
    class Position {
        int row, col;
        public Position(int x, int y) {
            this.row = x;
            this.col = y;
        }
    
        public boolean equals(Object other) {
            Position o = (Position) other;
            return this.row == o.row && this.col == o.col;
        }
        
        public int hashCode() {
            int res = 0;
            res = 31 * res + this.row;
            res = 31 * res + this.col;
            return res;
        }
    }

Log in to reply
 

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