Re: [闲聊] 每日LeetCode

楼主: Rushia (みけねこ的鼻屎)   2022-11-01 14:13:47
1706. Where Will the Ball Fall
给予一个二维阵列表示 2D 的 Ball Fall 游戏,每格意义如下:
1:\ 往右
-1:/ 往左
https://assets.leetcode.com/uploads/2019/09/26/ball.jpg
求出从每个位置的顶端放入一颗球最后该球会从哪个出口掉出来
如果球卡死没掉出来返回-1。
Example:
Input: grid =
[[1,1,1,-1,-1],[1,1,1,-1,-1],[-1,-1,-1,1,1],[1,1,1,1,-1],[-1,-1,-1,-1,-1]]
Output: [1,-1,-1,-1,-1]
Explanation: This example is shown in the photo.
Ball b0 is dropped at column 0 and falls out of the box at column 1.
Ball b1 is dropped at column 1 and will get stuck in the box between column 2
and 3 and row 1.
Ball b2 is dropped at column 2 and will get stuck on the box between column 2
and 3 and row 0.
Ball b3 is dropped at column 3 and will get stuck on the box between column 2
and 3 and row 0.
Ball b4 is dropped at column 4 and will get stuck on the box between column 2
and 3 and row 1.
思路:
1.起点在箱子顶端(第一列的每一行),判断放入时两边的方向是否一致,必须是
\ \ 或 / / 球才可以到下一格,若是右边的四种情况 \/ \/ \|(撞墙) |/
球才会卡死。
2.方向为右就检查右边的斜坡方向,方向为左就检查左边的,如果检查可以到下一格
就依照\ \ 或/ / 来决定球往下移动的时候是往左还往右。
3.最后检查y是否等于R,如果相等就表示他是从出口出来的,球的离开位置为x,否则
球为卡死设为 -1
Java Code:
class Solution {
public int[] findBall(int[][] grid) {
int R = grid.length, C = grid[0].length;
int[] res = new int[C];
for(int i = 0; i < C; i++) {
int x = i, y = 0;;
while (x < C && y < R) {
if(grid[y][x] == 1) {
if(x + 1 >= C || grid[y][x + 1] != 1)
break;
x++;
y++;
}
else {
if(x - 1 < 0 || grid[y][x - 1] != -1)
break;
x
作者: Jaka (Jaka)   2022-11-01 14:15:00
大师
作者: Mikotosama (鬼之子)   2022-11-01 14:17:00
笑了 这心得
作者: argorok (s.green)   2022-11-01 14:23:00
靠北 最后笑了
作者: TNPSCG (TNP)   2022-11-01 14:33:00
靠背 又是复制

Links booklink

Contact Us: admin [ a t ] ucptt.com