C
C#9mo 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;
}
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;
}
5 Replies
Unknown User
Unknown User9mo ago
Message Not Public
Sign In & Join Server To View
morry329#
morry329#OP9mo ago
Like this. I still don't undestand what is out of bound
No description
Angius
Angius9mo ago
What's 0 - 1?
No description
Unknown User
Unknown User9mo ago
Message Not Public
Sign In & Join Server To View
Angius
Angius9mo ago
Similarly, if you have 5 candies and I ask you for candu number -1, it's also out of bounds
Want results from more Discord servers?
Add your server