Sponsored
Sponsored
Use depth-first search (DFS) to simulate the movement of each ball from the top to the bottom, keeping track of the ball's column. If a ball encounters a 'V' shape or hits the wall, it gets stuck. This approach simulates the scenario for each ball individually.
Time Complexity: O(m * n), where m is the number of rows and n is the number of columns.
Space Complexity: O(n) for the result and recursion stack.
1public class Solution {
2 public int FindExit(int[][] grid, int row, int col) {
3 if (row == grid.Length) return col;
4 int nextCol = col + grid[row][col];
5 if (nextCol < 0 || nextCol == grid[0].Length || grid[row][nextCol] != grid[row][col]) return -1;
6 return FindExit(grid, row + 1, nextCol);
7 }
8
9 public int[] FindBall(int[][] grid) {
10 int n = grid[0].Length;
11 int[] result = new int[n];
12 for (int i = 0; i < n; i++) {
13 result[i] = FindExit(grid, 0, i);
14 }
15 return result;
16 }
17}
The C# solution employs a recursive FindExit method to simulate the path of the ball, closely mirroring the DFS strategy. The accumulated results for each column iteration form a straightforward reflection of whether the ball exited or got blocked.
Utilize nested loops to simulate the motion of each ball iteratively instead of using recursion. It tracks each movement step-by-step across the grid, calculates next positions, transitions to subsequent rows, and monitors for blockages or exits.
Time Complexity: O(m * n), driven by iterating through all cells.
Space Complexity: O(n), where n stands for the result array requirement.
1using namespace std;
class Solution {
public:
vector<int> findBall(vector<vector<int>>& grid) {
vector<int> result(grid[0].size(), 0);
for (int i = 0; i < grid[0].size(); ++i) {
int col = i;
for (int row = 0; row < grid.size(); ++row) {
int nextCol = col + grid[row][col];
if (nextCol < 0 || nextCol >= grid[0].size() || grid[row][nextCol] != grid[row][col]) {
col = -1;
break;
}
col = nextCol;
}
result[i] = col;
}
return result;
}
};
A straightforward transition allows the C++ version to iteratively simulate the function. A nested loop sequence helps identify whether each ball successfully traverses the grid or ends with it stuck condition - calculating step-by-step to retain accuracy.