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
  • 相关阅读:
    Mybaits 的优点
    mybatis中#{}和${}的区别
    springmvc工作流程
    request对象的主要方法有哪些
    如何决定选用HashMap还是TreeMap?
    队列和栈是什么,列出它们的区别?
    fail-fast与fail-safe有什么区别?
    Collections类是什么?
    哪些集合类提供对元素的随机访问?
    可以作为GC Roots的对象包括哪些
  • 原文地址:https://www.cnblogs.com/whatyouthink/p/13208960.html
Copyright © 2011-2022 走看看