Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions algorithms/cpp/WhereWilltheBallFall/WhereWilltheBallFall.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
// https://leetcode.com/problems/where-will-the-ball-fall/

class Solution {
public:
vector<int> findBall(vector<vector<int>>& grid) {
int N = grid.size();
int M = grid[0].size();
vector<int> res;

for(int ball=0;ball<grid[0].size();ball++){
int i = 0;
int j = ball;
while(i < N){
int cell = grid[i][j];
// go left or right according to current cell (1 or -1)
j += cell;
// if got out of matrix
if(j >= M || j < 0)
break;
// if adjacent cell is closed (eg. going left and current is right)
if(cell != grid[i][j])
break;
// go down one cell
i++;
}
// if got out safely. push column num ( j ) else push ( -1 )
i == N ? res.push_back(j) : res.push_back(-1);
}
return res;
}
};