Java DoublyLinkedList + Set + Queue Solution


  • 1
    X
    class SnakeNode {
        int row, col;
        SnakeNode pre;
        SnakeNode next;
        SnakeNode(int row, int col) {
            this.row = row;
            this.col = col;
            this.pre = null;
            this.next = null;
        }
    }
    
    public class SnakeGame {
        
        SnakeNode snakeHead;
        SnakeNode snakeTail;
        Set<Integer> snakeCell;
        Queue<int[]> foodList;
        Integer score, height, width;
    
        public SnakeGame(int width, int height, int[][] food) {
            
            snakeHead = new SnakeNode(0, 0);
            snakeTail = snakeHead;
            
            snakeCell = new HashSet<>();
            snakeCell.add(0);
            
            foodList = new LinkedList<int[]>();
            for(int[] i : food) {
                foodList.offer(i);
            }
            
            this.score = 0;
            this.height = height;
            this.width = width;
        }
    
    
        public int move(String direction) {
            
            int[] moveDir = new int[2];
            switch (direction) {
                case "U" : 
                    moveDir[0] = -1;
                    break;
                case "L" :
                    moveDir[1] = -1;
                    break;
                case "R" :
                    moveDir[1] = 1;
                    break;
                case "D" :
                    moveDir[0] = 1;
                    break;
                default:
                    break;
            }
            int newRow = snakeHead.row + moveDir[0];
            int newCol = snakeHead.col + moveDir[1];
    
            SnakeNode newHead = new SnakeNode(newRow, newCol);
            int headCode = newRow * width + newCol;
            int tailCode = snakeTail.row * width + snakeTail.col;
            
            if(newRow < 0 || newRow >= height || newCol < 0 || newCol >= width || snakeCell.contains(headCode) && headCode != tailCode) {
                return -1;
            }
                
            int[] nextFood = foodList.peek();
            
            newHead.next = snakeHead;
            snakeHead.pre = newHead;
            snakeHead = newHead;
            
            if(nextFood != null && newRow == nextFood[0] && newCol == nextFood[1]) {
                foodList.poll();
                snakeCell.add(headCode);
                score++;
            } else {
                snakeCell.remove(tailCode);
                snakeCell.add(headCode);
                snakeTail = snakeTail.pre;
                snakeTail.next = null;
            }
            
            return score;
        }
    }
    
    

Log in to reply
 

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