可以被一步捕获的棋子数

2024-12-06

题目:

给定一个 8 x 8 的棋盘,只有一个 白色的车,用字符 'R' 表示。棋盘上还可能存在白色的象 'B' 以及黑色的卒 'p'。空方块用字符 '.' 表示。

车可以按水平或竖直方向(上,下,左,右)移动任意个方格直到它遇到另一个棋子或棋盘的边界。如果它能够在一次移动中移动到棋子的方格,则能够 吃掉 棋子。

注意:车不能穿过其它棋子,比如象和卒。这意味着如果有其它棋子挡住了路径,车就不能够吃掉棋子。

返回白车将能 吃掉卒的数量

示例 1:

img

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

示例 2:

img

输入:[[".",".",".",".",".",".",".","."],[".","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:

img

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

提示:

  1. board.length == 8
  2. board[i].length == 8
  3. board[i][j] 可以是 'R''.''B''p'
  4. 只有一个格子上存在 board[i][j] == 'R'

思路:

从车出发,判断沿着上下左右能不能迟到卒即可

代码:

class Solution {
public:
    bool isValid(int row, int col) {
        if (0 <= row && row < 8 && 0 <= col && col < 8) return true;
        return false;
    }
    int numRookCaptures(vector<vector<char>>& board) {
        int startRow, startCol;
        for (int i = 0; i < 8; i++) {
            for (int j = 0; j < 8; j++) {
                if (board[i][j] == 'R') {
                    startRow = i;
                    startCol = j;
                    break;
                }
            }
        }
        int dire[4][2] = { {1, 0}, {-1, 0}, {0, 1}, {0, -1} };
        int ans = 0;
        for (int i = 0; i < 4; i++) {
            int curRow = startRow, curCol = startCol;
            while (isValid(curRow, curCol)) {
                // 出界 / 遇到任意的棋子就停下
                if (board[curRow][curCol] == 'p') {
                    ans++;
                    break;
                } else if (board[curRow][curCol] == 'B') {
                    break;
                }
                curRow += dire[i][0];
                curCol += dire[i][1];
            }
        }
        return ans;
    }
};