Available catch car

Available catch 999. car

On a 8 x 8 board, there is a white car (rook). It may also be available box, white elephant (bishop) and the black pawn (pawn). They are given to the character "R", ".", "B" and "p". The uppercase characters indicate White, Black lowercase characters are represented.

The car moves in chess rule: choose one of four basic directions (North, East, West and South), and then move in that direction until it choose to stop, or reach the edge of the board to move to the same square capture and death on the opposite color squares. In addition, the car can not be friendly with the other (white) like into the same box.

Returns the number of death in a car to be able to capture the move.

Example 1:

输入:[[".",".",".",".",".",".",".","."],[".",".",".","p",".",".",".","."],[".",".",".","R",".",".",".","p"],[".",".",".",".",".",".",".","."],[".",".",".",".",".",".",".","."],[".",".",".","p",".",".",".","."],[".",".",".",".",".",".",".","."],[".",".",".",".",".",".",".","."]]
输出:3
解释:
在本例中,车能够捕获所有的卒。

Example 2:

输入:[[".",".",".",".",".",".",".","."],[".","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",".","."],[".",".",".",".",".",".",".","."],[".",".",".",".",".",".",".","."]]
输出:0
解释:
象阻止了车捕获任何卒。

Example 3:

输入:[[".",".",".",".",".",".",".","."],[".",".",".","p",".",".",".","."],[".",".",".","p",".",".",".","."],["p","p",".","R",".","p","B","."],[".",".",".",".",".",".",".","."],[".",".",".","B",".",".",".","."],[".",".",".","p",".",".",".","."],[".",".",".",".",".",".",".","."]]
输出:3
解释: 
车可以捕获位置 b5,d6 和 f5 的卒。
#获取到车的位置,直接在4个方向进行遍历
class Solution:
    def numRookCaptures(self, board: List[List[str]]) -> int:
        if not board:
            return 0
        #找到车的起始位置
        for i,line in enumerate(board):
            for j,w in enumerate(line):
                if w == "R":
                    x,y = i,j
        count = 0
        #沿着一个方向运动,直到到达边界或者象、卒
        for (dx,dy) in [(-1,0),(1,0),(0,1),(0,-1)]:
            new_x = x+dx
            new_y = y+dy
            while not (new_x < 0 or new_x>=len(board) or new_y < 0 or new_y>=len(board[0])):
                if board[new_x][new_y] == "B":
                    break
                if board[new_x][new_y] == "p":
                    count += 1
                    break
                new_x += dx
                new_y += dy
        return count

Guess you like

Origin www.cnblogs.com/gongyanzh/p/12574459.html
car