# 1706

Jul 30th, 2021
748
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
1. class Solution {
2. public:
3.     int rsize, csize;
4.     vector<int> findBall(vector<vector<int>>& grid) {
5.         rsize = grid.size(); csize = grid[0].size();
6.         vector<int> ans(csize);
7.         for(int i=0; i<csize; i++)
8.             ans[i] = dfs(0, i, grid);
9.         return ans;
10.     }
11.
12.     bool check(int r, int c){
13.         if(r<0 || c<0 || r>=rsize || c>=csize) return false;
14.         return true;
15.     }
16.
17.     int dfs(int r, int c, vector<vector<int>> &grid){
18.         // If last row is exited.
19.         if(r == rsize)
20.             return c;
21.
22.         // Current cell should be valid.
23.         if(check(r, c)){
24.             // Check for direction of adjacent cell and also it's validity.
25.             if(grid[r][c] == 1 && check(r, c+1) && grid[r][c+1] == 1)
26.                 return dfs(r+1, c+1, grid);
27.             else if(grid[r][c] == -1 && check(r, c-1) && grid[r][c-1] == -1)
28.                 return dfs(r+1, c-1, grid);
29.         }
30.
31.         // Return -1 if no condition is applicable and the ball is stuck.
32.         return -1;
33.     }
34. };
RAW Paste Data