C++ solution || DFS || explained ✅
starIf you found this solution helpful please upvote\u2B50\n\nclass Solution {\npublic:\n    int dfs(int i, int j, vector>& grid){\n        //if i(row) is great
**starIf you found this solution helpful please upvote\u2B50\n**\nclass Solution {\npublic:\n    int dfs(int i, int j, vector<vector<int>>& grid){\n        //if i(row) is greater than the size of grid it means we are already out of the grid so we return the respective col\n        if(i >= grid.size()) return j;\n        \n        //to check left to right\n        //if there are two consecutive 1 present in the grid then only a ball can move downward\n        if(grid[i][j] == 1 && j+1 < grid[0].size() && grid[i][j+1] == 1)\n            return dfs(i+1, j+1, grid);\n        \n        //to check right to left\n        //if there are two -1 present in the grid then only a ball can move downward\n        else if(grid[i][j] == -1 && j-1 >= 0 && grid[i][j-1] == -1)\n            return dfs(i+1, j-1, grid);\n        \n        //else the ball will get stuck in the grid\n        else return -1;\n    }\n    \n    vector<int> findBall(vector<vector<int>>& grid) {\n        int rows = grid.size();\n        int cols = grid[0].size();\n        \n        //as number of balls are equal to the cols of the given grid so we initiate a vector of size cols\n        vector<int> ans(cols);\n        for(int i=0; i<cols; i++){\n            //for every ball we calculate their col from which they escape the grid\n            ans[i] = dfs(0, i, grid);\n        }\n        \n        return ans;\n    }\n};
['Depth-First Search', 'C++']