LCCUP——LCP63. 弹珠游戏
啊啊啊看完题解豁然开朗,还需要多做题,菜狗子
DIRS = ((0, 1), (1, 0), (0, -1), (-1, 0)) #右下左上
class Solution:
def ballGame(self, num: int, plate: List[str]) -> List[List[int]]:
n, m = len(plate), len(plate[0])
def check(x : int, y : int, d : int) -> bool :
left = num
while plate[x][y] != 'O' :
if left == 0 : return False
if plate[x][y] == 'E' :
d = (d + 1) % 4
if plate[x][y] == 'W' :
d = (d + 3) % 4
x += DIRS[d][0]
y += DIRS[d][1]
if not (0 <= x < n and 0 <= y < m):
return False
left -= 1
return True
ans = []
for i in range(1, m - 1) :
if plate[0][i] == '.' and check(0, i, 1) : ans.append([0, i])
if plate[n - 1][i] == '.' and check(n - 1, i, 3) : ans.append([n - 1, i])
for i in range(1, n - 1) :
if plate[i][0] == '.' and check(i, 0, 0) : ans.append([i, 0])
if plate[i][n - 1] == '.' and check(i, n - 1, 2) : ans.append([i, n - 1])
return ans
总结
从本题我学到了如下技巧
- 首先将那些容易出错的代码片段先写,防止脑子后面写成浆糊
- 对于图中控制方向的写法可以定义一个二维元组或者数组
DIRS = ((0, 1), (1, 0), (0, -1), (-1, 0)) #右下左上
,对于旋转来说通过模运算来实现,比如上面是顺时针的数组方向,对应0, 1, 2, 3,要改为逆时针则d = (d + 3) % 4,顺时针则d = (d + 1) % 4 - 洛谷有类似题(https://www.luogu.com.cn/problem/P1518)