Could anybody help understand why this java code fails one of the last test cases


  • 0
    T
    public class SnakeGame {
    
        int width, height;
        int[][] food;
        int row, col, foodIndex, score;
        /** 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;
            row = 0;
            col = 0;
            foodIndex = 0;
            score = 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")){
                row--;
            }else if(direction.equals("L")){
                col--;
            }else if(direction.equals("R")){
                col++;
            }else{
                row++;
            }
            int res = helper(row, col);
            return res;
            
        }
        
        private int helper(int row, int col){
            if(row<0 || col<0 || row>=height || col >= width) return -1;
            if(foodIndex==food.length) return score;
            if(row == food[foodIndex][0] && col == food[foodIndex][1]){
                score++;
                foodIndex++;
            }
            return score;
        }
    }
    
    /**
     * Your SnakeGame object will be instantiated and called as such:
     * SnakeGame obj = new SnakeGame(width, height, food);
     * int param_1 = obj.move(direction);
     */
    

    It fails the following test case:

    ["SnakeGame","move","move","move","move","move","move","move","move","move","move","move","move","move","move","move"]
    [[3,3,[[2,0],[0,0],[0,2],[0,1],[2,2],[0,1]]],["D"],["D"],["R"],["U"],["U"],["L"],["D"],["R"],["R"],["U"],["L"],["L"],["D"],["R"],["U"]]
    
    

    I tried to understand it in different ways but failed to pass this test.


Log in to reply
 

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