[每日一题] 161. 车的可用捕获量(模拟、方向数组、常规解法)

1. 题目来源

链接:999. 车的可用捕获量
来源:LeetCode

2. 题目说明

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

3. 题目解析

方法一:模拟+方向数组+常规解法

水题,就是找 R 上下左右四条路径中能不被 B 挡住的情况找到几个 p,这里只找四方向中第一次出现的 p 即可。

题目长,理解了就是真实的水题…练练方向数组还行。

首先,献上暴力解法。四个 while 搞定,采用 flag 判断是否为第一个 p,当然用 break 直接跳出本次 while 循环也是可以的。

参见代码如下:

// 执行用时 :0 ms, 在所有 C++ 提交中击败了100.00%的用户
// 内存消耗 :6.4 MB, 在所有 C++ 提交中击败了100.00%的用户

class Solution {
public:
    int numRookCaptures(vector<vector<char>>& board) {
        int cnt = 0, len = board.size();
        for (int i = 0; i < len; ++i) {
            for (int j = 0; j < len; ++j) {
                if (board[i][j] == 'R') {
                    int row = i, col = j, flag = 0;
                    while (row - 1 > 0 && board[row][col] != 'B') {
                        --row;
                        if (board[row][col] == 'p' and flag == 0) ++cnt, flag = 1;
                    }
                    row = i, col = j, flag = 0;
                    while (row + 1 < len && board[row][col] != 'B') {
                        ++row;
                        if (board[row][col] == 'p' and flag == 0) ++cnt, flag = 1;
                    }
                    row = i, col = j, flag = 0;
                    while (col - 1 > 0 && board[row][col] != 'B') {
                        --col;
                        if (board[row][col] == 'p' and flag == 0) ++cnt, flag = 1;
                    }
                    row = i, col = j, flag = 0;
                    while (col + 1 < len && board[row][col] != 'B') {
                        ++col;
                        if (board[row][col] == 'p' and flag == 0) ++cnt, flag = 1;
                    }
                    return cnt;
                }
            }
        }
        return 0;
    }
};

方向数组使用:

参见代码如下:

// 执行用时 :0 ms, 在所有 C++ 提交中击败了100.00%的用户
// 内存消耗 :6.2 MB, 在所有 C++ 提交中击败了100.00%的用户

class Solution {
public:
int dir[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
    int numRookCaptures(vector<vector<char>>& board) {
        int cnt = 0, len = board.size();
        for (int i = 0; i < len; ++i) {
            for (int j = 0; j < len; ++j) {
                if (board[i][j] == 'R') {
                   for (int k = 0; k < 4; ++k) {
                       int x = i, y = j;
                       while (1) {
                           x += dir[k][0];
                           y += dir[k][1];
                           if (x < 0 or x >=len or y < 0 or y>= 8 or board[x][y] == 'B') break;
                           if (board[x][y] == 'p') {
                               ++cnt;
                               break;
                           }
                       }
                   }
                   return cnt;
                }
            }
        }
        return 0;
    }
};
发布了391 篇原创文章 · 获赞 329 · 访问量 8万+

猜你喜欢

转载自blog.csdn.net/yl_puyu/article/details/105123368