Solution to the problem Leetcode: where-will-the-ball-fall

Abhishek Kumar
2 min readDec 28, 2020

Problem link: https://leetcode.com/contest/weekly-contest-221/problems/where-will-the-ball-fall/

Solution in C++

Solution to leetcode problem

class ballState {
public:
int ball_id, row, col;
bool stopped;
ballState(int ball_id, int row, int col) : ball_id(ball_id), row(row), col(col) {
stopped = false; // the ball is not stopped initially
}
bool willBallStop(vector<vector<int> > &grid, int pr, int pc, int nr, int nc) {
// pr == present row, nr = no_of_rows
// logic to decide if ball stops in this iteration
return (
(pc == 0 && grid[pr][pc] == -1) ||
(pc == nc-1 && grid[pr][pc] == 1) ||
(pc < nc-1 && grid[pr][pc] == 1 && grid[pr][pc+1] == -1) ||
(pc > 0 && grid[pr][pc] == -1 && grid[pr][pc-1] == 1)
);
}
};

class Solution {
public:
vector<int> findBall(vector<vector<int>>& grid) {
int no_of_rows = grid.size();
int no_of_columns = grid[0].size();
// assuming each ball descends with the same speed = 1 cell/sec
// Initially: at t=0, all balls are at the top of each respective cell
// in the first row
vector<ballState> ballStatesVector;
for (int i = 0; i < no_of_columns; i += 1) {
ballStatesVector.emplace_back(ballState(i, 0, i));
}

for (int t = 0; t < no_of_rows; t += 1) {
// from time T to T+1 / from top of Tth cell to top of (T+1)th cell in the first row
// iterate through states of all the balls
for (auto updatedBallState : ballStatesVector) {
if (!updatedBallState.stopped) {
if (updatedBallState.willBallStop(grid, updatedBallState.row, updatedBallState.col, no_of_rows, no_of_columns)) {
updatedBallState.stopped = true;
} else {
// update state of ball
updatedBallState.col += grid[updatedBallState.row][updatedBallState.col];
updatedBallState.row += 1;
}
ballStatesVector[updatedBallState.ball_id] = updatedBallState;
}
}
}

// check for balls which at the start of time t=r are at the head of rth row (imaginary) ie
// they are at end of (r-1)th row
vector<int> finalAnsVector;
for (auto finalBallState : ballStatesVector) {
if (finalBallState.stopped) {
finalAnsVector.push_back(-1);
} else {
finalAnsVector.push_back(finalBallState.col);
}
}
return finalAnsVector;
}
};

Hope the code is readable!!

Thanks for reading. If u still have doubts, please leave them in the comments below!!

--

--