20250215力扣每日一题

知识点

解题思路

  • 模拟
  • 当球进入一个格子内的时候,有两种情况:
    • 格子的挡板可以把球向右推,即该格内的数值为1
      • 如果右侧的格子挡板为-1,或者右侧为边界时,此时球无法继续下落,可以中止循环
      • 如果右侧的格子挡板为1,此时球可以下落
    • 格子的挡板可以把球左推,即该格内的数值为-1
      • 如果左侧的格子挡板为1,或者左侧为边界,此时球无法继续下落,可以中止循环
      • 如果右侧的格子挡板为-1,此时球可以下落
  • 循环执行上述模拟步骤,直至到达最底层

实现代码

class Solution {
public:
    vector<int> findBall(vector<vector<int>>& grid) {
        int m = grid.size(), n = grid[0].size();
        vector<int> ans(n, -1);

        for(int i = 0; i < n; i ++){
            int row = 0, col = i;
            for(; row < m; row ++){
                if(grid[row][col] == 1){
                    if(col + 1 >= n || grid[row][col + 1] == -1)
                        break;
                    else
                        col ++;
                }else{
                    if(col - 1 < 0 || grid[row][col - 1] == 1)
                        break;
                    else
                        col --;
                }
            }

            if(row == m)
                ans[i] = col;
        }
        return ans;
    }
};
// falling to the ground




Enjoy Reading This Article?

Here are some more articles you might like to read next:

  • Google Gemini updates: Flash 1.5, Gemma 2 and Project Astra
  • Displaying External Posts on Your al-folio Blog
  • 强化学习导论
  • 企业项目实训
  • 面试总结