class Solution: def calcu(self,ele:List[str],loc): index_p = [-1]*2 #只记录离R最近位置的p和B(左右) index_B = [-1]*2 left,right = 0,0 for i in range(len(ele)): if ele[i] is 'p': if i < loc: index_p[0]=i #左边的取最大值 else: if index_p[1]<0:index_p[1] = i #右边的取最小值 elif ele[i] is 'B': if i<loc: index_B[0]=i else: if index_B[1]<0:index_B[1]=i p0,p1,b0,b1 = index_p[0],index_p[1],index_B[0],index_B[1] #使用简便的符号标记,方便书写 if p0>=0:#p在R的左边 if b0>=0: #B在R的左边,有值 if p0<loc and b0<p0: left = 1 else: #B左边没有值 if p0<loc: left = 1 if p1>=0:#p在R的右边 if b1>=0:#B在R的右边,有值 if p1>loc and b1>p1: right = 1 else:#B右边没有值 if p1>loc: right = 1 return left,right def numRookCaptures(self, board: List[List[str]]) -> int: index_R_row = 0 index_R_col = 0 count = 0 col = [] row = [] for a in board: index_R_row += 1 if 'R' in a: for i in range(len(a)): if a[i]=='R': index_R_col = i col = [x[i] for x in board] row = a break break r1,r2 = self.calcu(row,index_R_col) r3,r4 = self.calcu(col,index_R_row-1) count = r1+r2+r3+r4 return count
40ms,13M
my god,写这个代码花了我半天时间,估计以后都不想看第二遍了。。。。。