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