999.可以被一步捕获的棋子数

【LetMeFly】999.可以被一步捕获的棋子数:模拟

力扣题目链接:https://leetcode.cn/problems/available-captures-for-rook/

给定一个 8 x 8 的棋盘,只有一个 白色的车,用字符 '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 的卒。

 

提示:

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

解题方法:模拟

一共分为两步:

  1. 遍历棋盘,遇到字符R时停下,并记录下起点下标
  2. 从起点开始分别向上下左右四个方向遍历,遇到边界或者遇到B停止。同时,遍历时若遇到p,则答案数量加一并停止。
  • 时间复杂度$O(mn)$,其中棋盘大小为$m\times n$
  • 空间复杂度$O(1)$

我的一个评论

AC代码

C++

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
const int directions[4][2] = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
class Solution {
public:
int numRookCaptures(vector<vector<char>>& board) {
int x, y;
for (x = 0; x < board.size(); x++) {
for (y = 0; y < board[0].size(); y++) {
if (board[x][y] == 'R') {
goto loop;
}
}
}
loop:;
int ans = 0;
for (int d = 0; d < 4; d++) {
for (int step = 1; ; step++) {
int nx = x + directions[d][0] * step;
int ny = y + directions[d][1] * step;
if (nx < 0 || nx >= board.size() || ny < 0 || ny >= board[0].size() || board[nx][ny] == 'B') {
break;
}
if (board[nx][ny] == 'p') {
ans++;
break;
}
}
}
return ans;
}
};

同步发文于CSDN和我的个人博客,原创不易,转载经作者同意后请附上原文链接哦~

Tisfy:https://letmefly.blog.csdn.net/article/details/144303138


999.可以被一步捕获的棋子数
https://blog.letmefly.xyz/2024/12/07/LeetCode 0999.可以被一步捕获的棋子数/
作者
Tisfy
发布于
2024年12月7日
许可协议