Leetcode 999. Available Captures for Rook

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Available Captures for Rook

2. Solution

解析:Version 1,先找到R,再分别统计四个方向上的p

  • Version 1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
class Solution:
def numRookCaptures(self, board: List[List[str]]) -> int:
length = 8
x = -1
y = -1
for i in range(length):
for j in range(length):
if board[i][j] == 'R':
x = i
y = j
break
if x != -1:
break

count = 0
row = board[x]
column = [board[i][y] for i in range(length)]
count += self.find(row, y-1, y+1, length)
count += self.find(column, x-1, x+1, length)
return count


def find(self, arr, i, j, length):
count = 0
while i > -1:
if arr[i] == 'p':
count += 1
break
elif arr[i] == 'B':
break
i -= 1
while j < length:
if arr[j] == 'p':
count += 1
break
elif arr[j] == 'B':
break
j += 1
return count

Reference

  1. https://leetcode.com/problems/available-captures-for-rook/
如果有收获,可以请我喝杯咖啡!