JZX轻语:简

LeetCode 1706 - 球会落何处

发表于2025年02月15日

#数组 #模拟

比较简单的模拟题,使用一个大小为m的数组记录每个小球当前所在的列(使用-1表示球已经被卡住),遍历每一轮(其实就是遍历每一行),分情况计算每一个小球的下一轮(行)的位置:

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

        for (int i = 0; i < m; ++i) {
            for (int j = 0; j < n; ++j) {  // iter balls, the j-th ball
                auto cur_col = ans[j];  // the current column of the j-th ball
                if (cur_col == -1) continue;  // cannot reach previously

                if (grid[i][cur_col] == -1 && (cur_col == 0 || grid[i][cur_col - 1] == 1)) ans[j] = -1;
                else if (grid[i][cur_col] == 1 && (cur_col == n - 1 || grid[i][cur_col + 1] == -1)) ans[j] = -1;
                else ans[j] += grid[i][cur_col];
            }
        }
        return ans;
    }
};

闪念标签:LC

题目链接:https://leetcode.cn/problems/where-will-the-ball-fall/