def numRockCaptures(board): """ :type board: List[List[str]] :rtype: int """ result = 0 index = 0 for i in board: if ‘R‘ in i: row = ‘‘.join(z for z in i if z != ‘.‘) if ‘Rp‘ in row: result += 1 if ‘pR‘ in row: result += 1 index = i.index("R") break col = ‘‘.join(board[i][index] for i in range(8) if board[i][index] != ‘.‘) if ‘Rp‘ in col: result += 1 if ‘pR‘ in col: result += 1 return result if __name__ == ‘__main__‘: """ 找到车的位置,然后将车所在的list转为str 判断str中是否存在‘Rp‘和‘pR‘ 然后再获取车所在列的list,将它转为str 判断str中是否存在‘Rp‘和‘pR‘ """ # test case board = [[".",".",".",".",".",".",".","."],[".",".",".","p",".",".",".","."],[".",".",".","R",".",".",".","p"],[".",".",".",".",".",".",".","."],[".",".",".",".",".",".",".","."],[".",".",".","p",".",".",".","."],[".",".",".",".",".",".",".","."],[".",".",".",".",".",".",".","."]] result = numRockCaptures(board) print(result)
Solution 2:
def numRockCaptures(board): """ :type board: List[List(str)] :reype: int """ for i in range(8): for j in range(8): if board[i][j] == ‘R‘: x0, y0 = i, j res = 0 for i, j in [[1, 0], [0, 1], [-1, 0], [0, -1]]: x, y = x0 + i, y0 + j while 0 <= x < 8 and 0 <= y < 8: if board[x][y] == ‘p‘: res += 1 break if board[x][y] != ‘.‘: break x, y = x + i, y + j return res if __name__ == ‘__main__‘: """ 先找到车R的位置 然后依次从四个方向去遍历 """ # test case board = [[".",".",".",".",".",".",".","."],[".","p","p","p","p","p",".","."],[".","p","p","B","p","p",".","."],[".","p","B","R","B","p",".","."],[".","p","p","B","p","p",".","."],[".","p","p","p","p","p",".","."],[".",".",".",".",".",".",".","."],[".",".",".",".",".",".",".","."]] print(numRockCaptures(board))
999.Available Capture for rook
原文:https://www.cnblogs.com/mrjoker-lzh/p/10560576.html