-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfindBall.cpp
More file actions
46 lines (46 loc) · 1.34 KB
/
findBall.cpp
File metadata and controls
46 lines (46 loc) · 1.34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
class Solution {
public:
enum Dir {
DOWN, LEFT, RIGHT
};
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 x = 0, y = i;
Dir d = DOWN;
while (x < m && y >= 0 && y < n) {
switch (d) {
case DOWN:
if (grid[x][y] == 1) {
++y;
d = RIGHT;
}
else {
--y;
d = LEFT;
}
break;
case LEFT:
if (grid[x][y] == -1) {
++x;
d = DOWN;
}
else y = -1;
break;
case RIGHT:
if (grid[x][y] == 1) {
++x;
d = DOWN;
}
else y = -1;
break;
default:
break;
}
}
if (x == m) ans[i] = y;
}
return ans;
}
};