[leetcode] 球会落何处 模拟

在这里插入图片描述
给出一个矩阵,里面的值为-1 or 1
-1的时候是从左上到右下,1的时候是从左下到右上
当一个球从上方x(0 < x < m)放入之后,从哪个出口掉落还是无法从出口掉落

能通过的情况为:

  1. / / 即某条线为’/’,其左边的线也是’/’,箭头所指为当前斜线
      {\ }  
  2. \ \ 即当前线为’’,其右边的线也是’’,箭头所指为当前斜线
    {}
    但是还要注意边界问题

Code:

class Solution {
public:
    vector<int> findBall(vector<vector<int>>& grid) {
        int n = grid.size(), m = grid[0].size();
        vector<int> ans;
        for(int i = 0; i < m;i ++) {
            int x = 0,y = i;
            while(x < n && y >= 0 && y < m) {
                if(y >= 1 && grid[x][y] == grid[x][y-1] && grid[x][y] == -1) { //  '/'
                    ++ x;
                    -- y;
                }else if(y < m - 1 && grid[x][y] == grid[x][y+1] && grid[x][y] == 1) { //  '\'
                    ++ x;
                    ++ y;
                }
                else break;
            }
            if(x == n) ans.push_back(y);
            else ans.push_back(-1);
        }
        return ans;
    }
};

在这里插入图片描述

posted @ 2022-04-26 21:36  PushyTao  阅读(12)  评论(0编辑  收藏  举报