1.DFS
该题我们可以通过“跟着”球的路径走,我们通过仔细审题,我们不难发现我们可以使用DFS解决,不过这里在判断球往哪个方向走的时候要注意是由球自身所在格子和左右两边的格子决定的,比如说如果球自身所在位置grid[ x ][ y ]是1,这时候球会往右下走,如果 grid[ x ][ y+1 ]也是1的话,球就可以到达grid[ x+1 ][ y +1 ],否则球就会卡住,同理左边情况也一样
对了记得考虑是否越界来判断是不是在边界卡住了
class Solution {
public:
void dfs(vector<vector<int>>& grid, int x, int y, int n, int m, int i, vector<int>& ans)
{
if (x == n)//球到达终点
{
ans[i] = y;
return;
}
if (grid[x][y] == 1)//分右边和左边的情况讨论
{
if (y + 1 >= m)//边界卡住越界
{
ans[i] = -1;
return;
}
if (grid[x][y + 1] == 1)//可以往右下走
{
dfs(grid, x + 1, y + 1, n, m, i, ans);
}
else//卡住
{
ans[i] = -1;
return;
}
}
else if (grid[x][y] == -1)//左边情况讨论
{
if (y - 1 < 0)
{
ans[i] = -1;
return;
}
if (grid[x][y - 1] == -1)
{
dfs(grid, x + 1, y - 1, n, m, i, ans);
}
else
{
ans[i] = -1;
return;
}
}
}
vector<int> findBall(vector<vector<int>>& grid) {
int n, m;
n = grid.size();
m = grid[0].size();
vector<int>ans(m);
for (int i = 0; i < m; i++)//dfs每一个球
{
dfs(grid, 0, i, n, m, i, ans);
}
return ans;
}
};
2.模拟
思路
我们依次判断每个球的最终位置。对于每个球,从上至下判断球位置的移动方向。在对应的位置,如果挡板向右偏,则球会往右移动;如果挡板往左偏,则球会往左移动。若移动过程中碰到侧边或者V 型,则球会停止移动,卡在箱子里。如果可以完成本层的移动,则继续判断下一层的移动方向,直到落出箱子或者卡住。
class Solution {
public://模拟
vector<int> findBall(vector<vector<int>>& grid) {
int m=grid[0].size();//列
int n=grid.size();//行
vector<int>ans(m);
for(int j=0;j<m;j++)//遍历所有球
{
int col=j;//球的位置的列坐标
for(int i=0;i<n;i++)//遍历行
{
int dir=grid[i][col];//每次球所在位置是向右还是向左
col+=dir;//更新球的列坐标
//注意此时grid[i][col] != dir这个式子中的col已经改变但是行坐标还没变
if(col<0||col==m||grid[i][col] != dir)//球是否越界 或者 球是否被V卡住
{
col=-1;
break;
}
}
ans[j]=col;
}
return ans;
}
};