1.3 KiB
1.3 KiB
| title | date | tags | categories | |
|---|---|---|---|---|
| leetcode-999 | 2020-03-30 21:03:25 |
|
leetcode |
999. 可以被一步捕获的棋子数
遍历一遍找到车的坐标,然后按上下左右四个方向循环一下看碰到的第一个棋子是什么。
class Solution:
def numRookCaptures(self, board) -> int:
i = j = 0
for row in board:
if 'R' in row:
break
i += 1
j = row.index('R')
count = 0
# right
for x in range(j + 1, 8):
if row[x] == 'p':
count += 1
break
if row[x] == 'B':
break
# left
for x in range(j, 0, -1):
if row[x] == 'p':
count += 1
break
if row[x] == 'B':
break
# up
for x in range(i, 0, -1):
if board[x][j] == 'p':
count += 1
break
if board[x][j] == 'B':
break
# down
for x in range(i+1, 8):
if board[x][j] == 'p':
count += 1
break
if board[x][j] == 'B':
break
return count
#36 ms 13.6 MB
问题不难,官方解答中给了一个方向数组的概念,上下左右是 (0, 1) (0, -1) (-1, 0) (1, 0),有点像向量的意思。走的路线等于方向数组乘以步数。