C
C#2mo ago
morry329#

A small hiccup for the LeetCode puzzle Where the ball will fall

Link to the original puzzle https://leetcode.com/problems/where-will-the-ball-fall/ My code does not print out the right output just yet
public class ZigZagBallFallsTry
{

public int[] FindBall(int[][] grid)
{
int col = grid[0].Length-1;
int row = grid.Length-1;
int[] result = new int[col];

for (int i = 0; i < col; i++)
{
result[i] = BallHelp(grid, row, col);
}

return result;

}

private int BallHelp(int[][] grid, int row, int col)
{
int currRow = 0;
int currCol = col;

while (currRow <= row)
{
if (grid[currRow][currCol] == 1)
{
if (currCol == col || grid[currRow][currCol + 1] == -1)
{
return -1;
}
else
{
currCol++;
currRow++;
}
}
else if (grid[currRow][currCol] == -1)
{
if (currCol == 0 || grid[currRow][currCol - 1] == 1)
{
return -1;
}
else
{
currCol--;
currRow++;
}
}
else
{
currRow++;
}
}

return currCol;
}

}
public class ZigZagBallFallsTry
{

public int[] FindBall(int[][] grid)
{
int col = grid[0].Length-1;
int row = grid.Length-1;
int[] result = new int[col];

for (int i = 0; i < col; i++)
{
result[i] = BallHelp(grid, row, col);
}

return result;

}

private int BallHelp(int[][] grid, int row, int col)
{
int currRow = 0;
int currCol = col;

while (currRow <= row)
{
if (grid[currRow][currCol] == 1)
{
if (currCol == col || grid[currRow][currCol + 1] == -1)
{
return -1;
}
else
{
currCol++;
currRow++;
}
}
else if (grid[currRow][currCol] == -1)
{
if (currCol == 0 || grid[currRow][currCol - 1] == 1)
{
return -1;
}
else
{
currCol--;
currRow++;
}
}
else
{
currRow++;
}
}

return currCol;
}

}
The output is -1, -1, -1, -1 whilst it is supposed to be 1, -1, -1, -1, -1. The input here is 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]]` Could anyone kindly point me in the right direction?
0 Replies
No replies yetBe the first to reply to this messageJoin