Re: [閒聊] 每日LeetCode已回收
※ 引述《pandix (麵包屌)》之銘言:
: 1706. Where Will the Ball Fall
: 調皮的龍大把一排彈珠丟到箱子裡,想看有幾個彈珠能掉到底部,因為他真的很調皮
: 彈珠落下的規則參考 https://assets.leetcode.com/uploads/2019/09/26/ball.jpg

: 可以想像成箱子的每一格都有一個檔板
: 都收到說明了吧,給我回傳每個彈珠的最後位置,卡在箱子裡的話就是-1
: Example 1:
: 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]
: 就是上面那張圖
用兩個迴圈跑每個彈珠的每一次掉落,用x和y紀錄所在位置,
只要遇到卡住的就在res寫入-1,然後break去下一顆彈珠,
否則就讓彈珠前往下一層,最後能夠抵達底部的,就在res寫入所在的x
---
C++:
class Solution {
public:
vector<int> findBall(vector<vector<int>>& grid) {
int m = grid.size();
int n = grid[0].size();
vector<int> res;
for (int i = 0; i < n; i++) {
int x = i, y = 0;
for (int j = 0; j < m; j++) {
if (grid[y][x] == 1){
if (x == n - 1) {
res.push_back(-1);
break;
}
else if (grid[y][x + 1] == -1) {
res.push_back(-1);
break;
}
else if (grid[y][x + 1] == 1) {
x++;
y++;
}
}
else if (grid[y][x] == -1) {
if (x == 0) {
res.push_back(-1);
break;
}
else if (grid[y][x - 1] == 1) {
res.push_back(-1);
break;
}
else if (grid[y][x - 1] == -1){
x--;
y++;
}
}
}
if (y == m) res.push_back(x);;
}
return res;
}
};
---
python3:
class Solution:
def findBall(self, grid: List[List[int]]) -> List[int]:
m = len(grid)
n = len(grid[0])
res = []
for i in range(n):
x = i
y = 0
for j in range(m):
if (grid[y][x] == 1 and x == n - 1) or (grid[y][x] == -1 and x
== 0):
res.append(-1)
break
elif grid[y][x] == 1 and grid[y][x + 1] == -1:
res.append(-1)
break
elif grid[y][x] == -1 and grid[y][x - 1] == 1:
res.append(-1)
break
elif grid[y][x] == 1:
x += 1
y += 1
else:
x -= 1
y += 1
if y == m:
res.append(x)
return res
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 125.228.246.249 (臺灣)
※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1667314439.A.D9A.html
討論串 (同標題文章)
本文引述了以下文章的的內容:
完整討論串 (本文為第 79 之 719 篇):