首页 > 其他 > 详细

999.Available Capture for rook

时间:2019-03-19 19:03:50      阅读:152      评论:0      收藏:0      [点我收藏+]
999.Available Captures for Rook
 
车的可用捕获量

 

在一个8 × 8的棋盘上,有一个白色车(rook),也可能有空方块,白色的象(bishop)和黑色的卒(pawn)。它们分别以字符“R”,“.”,“B”和“p”给出。大写字符表示白棋,小写字符表示黑棋。</br>
车按国际象棋中的规则移动:它选择四个基本方向中的一个(北,东,西和南),然后朝那个方向移动,直到它选择停止、到达棋盘的边缘或移动到同一方格上颜色相反的卒。另外,车不能与其他友方(白色)象进入同一个方格。<br>返回车能够在一次移动中捕获到的卒的数量。

 

示例:

技术分享图片

 

输入:[[".",".",".",".",".",".",".","."],[".",".",".","p",".",".",".","."],[".",".",".","R",".",".",".","p"],[".",".",".",".",".",".",".","."],[".",".",".",".",".",".",".","."],[".",".",".","p",".",".",".","."],[".",".",".",".",".",".",".","."],[".",".",".",".",".",".",".","."]]
 
输出:3
 
解释:在本例中,车能够捕获所有的卒。
 
Solution 1:
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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!