C
C#3mo ago
morry329#

Not able to pass the test case correctly

The link to the original task https://leetcode.com/problems/where-will-the-ball-fall/ This is my WIP code
public class ZigZagBallFallsTry
{
public int[] FindBall(int[][] grid)
{
int m = grid.Length - 1;
int n = grid[0].Length - 1;

int[] result = new int[grid[0].Length]; // Initialize result array with correct size

for (int row = 0; row <= m; row++) // Loop until row <= m
{
result[row] = RecordBallMovements(grid, m, n); // Pass row index to RecordBallMovements
}

return result;
}

private int RecordBallMovements(int[][] grid, int m, int n)
{
int helperCol = 0; // Initialize helperCol here
for (int helperRow = 0; helperRow < m; helperRow++) // Loop until helperRow <= row
{
for (; helperCol >= 0 && helperCol <= n; helperCol++) // Correct loop condition and increment helperCol
{
if (grid[helperRow][helperCol] == 1)
{
if (helperCol == n || grid[helperRow][helperCol + 1] == -1) // Use == instead of >
{
return -1;
break;
}
}
else if (grid[helperRow][helperCol] == -1)
{
if (helperCol == 0 || grid[helperRow][helperCol - 1] == 1) // Use == instead of <
{
return -1;
break;
}
helperCol--; // Decrement helperCol for left movement
}
}
}
return helperCol;
}


}
public class ZigZagBallFallsTry
{
public int[] FindBall(int[][] grid)
{
int m = grid.Length - 1;
int n = grid[0].Length - 1;

int[] result = new int[grid[0].Length]; // Initialize result array with correct size

for (int row = 0; row <= m; row++) // Loop until row <= m
{
result[row] = RecordBallMovements(grid, m, n); // Pass row index to RecordBallMovements
}

return result;
}

private int RecordBallMovements(int[][] grid, int m, int n)
{
int helperCol = 0; // Initialize helperCol here
for (int helperRow = 0; helperRow < m; helperRow++) // Loop until helperRow <= row
{
for (; helperCol >= 0 && helperCol <= n; helperCol++) // Correct loop condition and increment helperCol
{
if (grid[helperRow][helperCol] == 1)
{
if (helperCol == n || grid[helperRow][helperCol + 1] == -1) // Use == instead of >
{
return -1;
break;
}
}
else if (grid[helperRow][helperCol] == -1)
{
if (helperCol == 0 || grid[helperRow][helperCol - 1] == 1) // Use == instead of <
{
return -1;
break;
}
helperCol--; // Decrement helperCol for left movement
}
}
}
return helperCol;
}


}
The output for this code is ==> -1 ==> -1 ==> -1 ==> -1 ==> -1 But it was supposed to be ==> 1 ==> -1 ==> -1 ==> -1 ==> -1` instead I don't understand why my code stores -1 instead of 1 at the first index on my array. Could anyone kindly point me in the right direction?
2 Replies
bebopper
bebopper3mo ago
What are your grid inputs?
morry329#
morry329#3mo ago
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]]