share my java solution!


  • 0
    T
    public class SnakeGame {
        Map<String,int[]> map=new HashMap<>();
        Deque<Integer> dq=new ArrayDeque<>();
        Set<Integer> set=new HashSet<>();
        int width;
        int height;
        int count=0;
        int[][] food;
        int index=0;
        
        /** 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.width=width;
            this.height=height;
            this.food=food;
            
            
            map.put("U",new int[]{-1,0});
            map.put("L",new int[]{0,-1});
            map.put("R",new int[]{0,1});
            map.put("D",new int[]{1,0});
            
            dq.offerLast(0);
            set.add(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 top=dq.peekLast();
            int[] dir=map.get(direction);
            
            int x=top/width+dir[0];
            int y=top%width+dir[1];
            
            if(x<0 || x>=height || y<0 || y>=width){
                return -1;
            }
            
            if(index<food.length && x==food[index][0] && y==food[index][1]){
                count++;
                dq.offerLast(x*width+y);
                set.add(x*width+y);
                index++;
                return count;
            }else{
                set.remove(dq.pollFirst());
                if(set.contains(x*width+y)){
                    return -1;
                }
                
                set.add(x*width+y);
                dq.offerLast(x*width+y);
                
            }
            
            return count;
            
        }
    }
    
    /**
     * 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.