Ссылка на проблему: https://leetcode.com/contest/weekly-contest-221/problems/where-will-the-ball-fall/

Решение на C ++

class ballState {
public:
int ball_id, row, col;
bool остановлен;
ballState (int ball_id, int row, int col): ball_id (ball_id), row ( строка), столбец (столбец) {
остановлен = ложь; // изначально мяч не останавливается
}
bool willBallStop (vector ‹vector ‹int›› & grid, int pr, int pc, int nr, int nc) {
// pr = = текущая строка, nr = no_of_rows
// логика для определения остановки мяча в этой итерации
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) < br />);
}
};

class Решение {
public:
vector ‹int› findBall (vector ‹vector ‹int›› & grid) {
int no_of_rows = grid.size ();
int no_of_columns = grid [0] .size ();
// предполагая, что каждый шар опускается с одинаковой скоростью = 1 ячейка / сек
// Первоначально: при t = 0 все шары находятся вверху каждого соответствующего ячейка
// в первой строке
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) {
// от времени T до T + 1 / от вершины T-й ячейки до вершины (T + 1) -й ячейки в первой строке
// итерация по состояниям всех шаров
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 {
// обновить состояние мяча
updatedBallState.col + = grid [updatedBallState.row] [updatedBallState.col];
updatedBallState.row + = 1;
}
ballStatesVector [updatedBallState.ball_id] = updatedBallState;
}
}
}

// Проверяем шары, которые в начале времени t = r находятся в начале r-й строки (воображаемой), т.е.
// они находятся в конце (r-1) -й строки
vector ‹int› finalAnsVector;
for (auto finalBallState: ballStatesVector) {
if (finalBallState.stopped) {
finalAnsVector.push_back (-1);
} else {
finalAnsVector.push_back (finalBallState.col);
}
}
return finalAnsVector;
}
};

Надеюсь, код читабельный !!

Спасибо за прочтение. Если у вас остались сомнения, оставьте их в комментариях ниже !!