LeetCode #999 车的可用捕获量 方向数组

LeetCode #999 车的可用捕获量

题目描述

在一个 8 x 8 的棋盘上,有一个白色车(rook)。也可能有空方块,白色的象(bishop)和黑色的卒(pawn)。它们分别以字符 “R”,“.”,“B” 和 “p” 给出。大写字符表示白棋,小写字符表示黑棋。

车按国际象棋中的规则移动:它选择四个基本方向中的一个(北,东,西和南),然后朝那个方向移动,直到它选择停止、到达棋盘的边缘或移动到同一方格来捕获该方格上颜色相反的卒。另外,车不能与其他友方(白色)象进入同一个方格。

返回车能够在一次移动中捕获到的卒的数量。

示例 1:
在这里插入图片描述

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

示例 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
解释:
象阻止了车捕获任何卒。

示例 3:
在这里插入图片描述

输入:[[".",".",".",".",".",".",".","."],[".",".",".","p",".",".",".","."],[".",".",".","p",".",".",".","."],["p","p",".","R",".","p","B","."],[".",".",".",".",".",".",".","."],[".",".",".","B",".",".",".","."],[".",".",".","p",".",".",".","."],[".",".",".",".",".",".",".","."]]
输出:3
解释: 
车可以捕获位置 b5,d6 和 f5 的卒。

方法一:方向数组

由于车每次移动只会造成一个方向的增量,如向北走一步 x 轴坐标 -1y 轴坐标不变,所以可以用 (-1, 0) 表示车向北方向走一步的增量,其他三个方向同理,建立方向数组

class Solution:
    def numRookCaptures(self, board: List[List[str]]) -> int:
        for i in range(len(board)):
            if 'R' in board[i]:
                row = i
                break
        col = board[row].index('R')
        # 定义方向数组
        dx, dy = [1, 0, -1, 0], [0, 1, 0, -1]

        count = 0
        for i in range(4):
        	# step 为步长
            step = 1
            while True:
                tx = row + dx[i] * step
                ty = col + dy[i] * step
                if tx < 0 or tx >= 8 or ty < 0 or ty >= 8 or board[tx][ty] == 'B':
                    break
                if board[tx][ty] == 'p':
                    count += 1
                    break
                step += 1 
        return count
  • 时间复杂度:O(N2)O(N^2)
  • 空间复杂度:O(1)O(1)

方法二

题解里看到的,将列表转换为字符串,通过查询子串是否存在来判断数量

class Solution:
    def numRookCaptures(self, board: List[List[str]]) -> int:
        for i in range(8):
            if 'R' in board[i]:
                row = i
                break
        col = board[row].index('R')
        
        count = 0
        # 车所在行
        s = ''.join(board[row])
        s = s.replace('.','')
        if 'pR' in s:
            count += 1
        if 'Rp' in s:
            count += 1
        # 车所在列
        s = ''.join(i[col] for i in board)
        s = s.replace('.','')
        if 'pR' in s:
            count += 1
        if 'Rp' in s:
            count += 1

        return count
发布了71 篇原创文章 · 获赞 2 · 访问量 1492
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 游动-白 设计师: 上身试试

分享到微信朋友圈

×

扫一扫,手机浏览