Skip to content

Instantly share code, notes, and snippets.

@dluciano
Last active November 1, 2022 20:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dluciano/5345cd7c7453a58e126889dd80399106 to your computer and use it in GitHub Desktop.
Save dluciano/5345cd7c7453a58e126889dd80399106 to your computer and use it in GitHub Desktop.
1706. Where Will the Ball Fall
public class Solution {
public int[] FindBall(int[][] grid) {
var ROWS = grid.Length;
var COLS = grid[0].Length;
var result = new int[COLS];
// [ball_id, ball_pos]
var balls = new Queue<int[]>();
for(var col = 0; col < COLS; ++col)
balls.Enqueue(new int[]{ col, col });
for(var row = 0; row < ROWS && balls.Count > 0; ++row){
var sz = balls.Count;
while(sz > 0){
var ball = balls.Dequeue();
var ballId = ball[0];
var ballColPosition = ball[1];
var hitLeftWall = grid[row][ballColPosition] == -1 && ballColPosition - 1 < 0;
var hitRightWall = grid[row][ballColPosition] == 1 && ballColPosition + 1 >= COLS;
if(hitLeftWall || hitRightWall){
sz--;
continue;
}
var isVFromLeft = grid[row][ballColPosition] == -1 && grid[row][ballColPosition - 1] == 1;
var isVFromRight = grid[row][ballColPosition] == 1 && grid[row][ballColPosition + 1] == -1;
if(isVFromLeft || isVFromRight){
sz--;
continue;
}
balls.Enqueue(new int[]{ ballId, ballColPosition + grid[row][ballColPosition] });
sz--;
}
}
for(var i = 0; i < COLS; ++i)
result[i] = -1;
while(balls.TryDequeue(out var ball))
result[ball[0]] = ball[1];
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment