Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution {
- public:
- int rsize, csize;
- vector<int> findBall(vector<vector<int>>& grid) {
- rsize = grid.size(); csize = grid[0].size();
- vector<int> ans(csize);
- for(int i=0; i<csize; i++)
- ans[i] = dfs(0, i, grid);
- return ans;
- }
- bool check(int r, int c){
- if(r<0 || c<0 || r>=rsize || c>=csize) return false;
- return true;
- }
- int dfs(int r, int c, vector<vector<int>> &grid){
- // If last row is exited.
- if(r == rsize)
- return c;
- // Current cell should be valid.
- if(check(r, c)){
- // Check for direction of adjacent cell and also it's validity.
- if(grid[r][c] == 1 && check(r, c+1) && grid[r][c+1] == 1)
- return dfs(r+1, c+1, grid);
- else if(grid[r][c] == -1 && check(r, c-1) && grid[r][c-1] == -1)
- return dfs(r+1, c-1, grid);
- }
- // Return -1 if no condition is applicable and the ball is stuck.
- return -1;
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment