Java ArrayList solution


  • 0
    H
     public class SnakeGame  {
        int width;
        int height;
        int col;
        int row;
        int[][] food;
        List<List<Integer>> body;
        int foodIndex;
    
        public SnakeGame(int width, int height, int[][] food) {
            body = new ArrayList<>();
            body.add(Arrays.asList(0, 0));
            col=0;
            row=0;
            this.width = width;
            this.height = height;
            this.food = food;
            this.foodIndex=0;
        }
        public int move(String direction) {
            switch (direction){
                case "R": col++;
                    break;
                case "L": col--;
                    break;
                case "U": row--;
                    break;
                case "D": row++;
                    break;
            }
    
            if(isValid()){
                body.add(0, Arrays.asList(col, row));
                if(foodIndex<food.length && row ==food[foodIndex][0] && col ==food[foodIndex][1]){
                    foodIndex=foodIndex+1;
                }else {
                    body.remove(body.size()-1);
                }
            } else
                return -1;
            return foodIndex;
        }
    
        private boolean isValid(){
            if(col <0|| row <0|| col >=width|| row >=height)
                return false;
            // check head to body is not valid except to tail
            for(int i=0;i<body.size()-1;i++){
                if(col ==body.get(i).get(0)&& row ==body.get(i).get(1))
                    return false;
            }
            return true;
        }
    }

Log in to reply
 

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