zoukankan      html  css  js  c++  java
  • 999. Available Captures for Rook

    On an 8 x 8 chessboard, there is one white rook.  There also may be empty squares, white bishops, and black pawns.  These are given as characters 'R', '.', 'B', and 'p' respectively. Uppercase characters represent white pieces, and lowercase characters represent black pieces.

    The rook moves as in the rules of Chess: it chooses one of four cardinal directions (north, east, west, and south), then moves in that direction until it chooses to stop, reaches the edge of the board, or captures an opposite colored pawn by moving to the same square it occupies.  Also, rooks cannot move into the same square as other friendly bishops.

    Return the number of pawns the rook can capture in one move.

    8 * 8的棋盘,上面有R,.,B,p分别代表 rook, 空格子, bishops, black pawns, R的移动规则是直线移动无限格,但不能吃B,求R移动一次,能吃哪些p。

    我感觉问题描述上有点歧义,其实就是想问R的四个方向是否都有p且中间没有B阻挡。

    class Solution(object):
        def find_p(self, board, i, j, direction):
            while i < len(board) and i >= 0 and j < len(board[0]) and j >= 0 and board[i][j] != 'B':
                if board[i][j] == 'p':
                    return 1
                i += direction[0]
                j += direction[1]
            return 0
        
        def numRookCaptures(self, board):
            """
            :type board: List[List[str]]
            :rtype: int
            """
            ans = 0
            directions = [[0, 1], [0, -1], [1, 0], [-1, 0]]
            for i in range(len(board)):
                for j in range(len(board[i])):
                    if board[i][j] == 'R':
                        for direction in directions:
                            ans += self.find_p(board, i, j, direction)
                        break
            return ans
  • 相关阅读:
    递归的形式过程
    c/c++程序员常见面试题分析(转)
    深入理解递归函数的调用过程(转)
    C语言union关键字
    中国象棋(java)
    求树中最低的公共祖先
    什么是Complement(补码)?
    LoadRunner,各协议之间的区别
    淘宝模板制作[店铺装修]学习过程+心得
    Tips of QTP
  • 原文地址:https://www.cnblogs.com/whatyouthink/p/13208960.html
Copyright © 2011-2022 走看看