C#C
C#2y ago
morry329#

IndexOutOfBoundsException triggered | LeetCode Where will the ball fall

Link to the puzzle description https://leetcode.com/problems/where-will-the-ball-fall/description/

I have been fighting with this puzzle for more than a month. Still my code cannot output correctly.
I tried this testcase
Input: grid = [[1,1,1,-1,-1],[1,1,1,-1,-1],[-1,-1,-1,1,1],[1,1,1,1,-1],[-1,-1,-1,-1,-1]] Output: [1,-1,-1,-1,-1]

And my WIP code (it triggers IndexOutOfBoundsException at line int currRow = 0. Could anyone kindly point me in the right direction?:

public int[] FindBall(int[][] grid){
        int col = grid[0].Length;
        int row= grid.Length;
        int[] result = new int[col];
     
        for(int i=0; i< col; i++){
            result [i]= Helper(grid,row,col);
        }

        return result;
    }

    public int Helper(int[][] grid, int row, int col){
        int currCol = 0;
        int currRow = 0; //OutOfBoundsException
        while(currRow < row){
            if (grid[currRow][currCol]==1){
                if(currCol == col - 1 || grid[currRow][currCol+1]==-1){
                    return -1;
                    break;
                } else {
                    currCol++;
                    currRow++;
                }
            } else if (grid[currRow][currCol] ==-1){
                if(currCol <0 || grid[currRow][currCol-1]==1){
                    return -1;
                    break;
                } else {
                    currCol--;
                    currRow++;
                }
            } 
            currRow++;
        }
        if(currRow==row){
            currCol = grid[currRow][currCol];
        } 
        return currCol;
    }
Was this page helpful?