-
发表于 2025.02.15
-
比较简单的模拟题,使用一个大小为
m
的数组记录每个小球当前所在的列(使用-1
表示球已经被卡住),遍历每一轮(其实就是遍历每一行),分情况计算每一个小球的下一轮(行)的位置:-
如果所在的单元格为
1
(形状为\
),且小球处于最后一列或者右边的单元格为-1
(形状为/
),则卡住; -
如果所在的单元格为
-1
(形状为/
),且小球处于第一列或者右边的单元格为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 题目链接
-