【LeetCode】999. 可以被一步捕获的棋子数(C++)

999. 可以被一步捕获的棋子数(C++)

1 题目描述

在一个 8 x 8 的棋盘上,有一个白色的车(Rook),用字符 ‘R’ 表示。棋盘上还可能存在空方块,白色的象(Bishop)以及黑色的卒(pawn),分别用字符 ‘.’,‘B’ 和 ‘p’ 表示。不难看出,大写字符表示的是白棋,小写字符表示的是黑棋。
车按国际象棋中的规则移动。东,西,南,北四个基本方向任选其一,然后一直向选定的方向移动,直到满足下列四个条件之一:

  • 棋手选择主动停下来。
  • 棋子因到达棋盘的边缘而停下。
  • 棋子移动到某一方格来捕获位于该方格上敌方(黑色)的卒,停在该方格内。
  • 车不能进入/越过已经放有其他友方棋子(白色的象)的方格,停在友方棋子前。
  • 你现在可以控制车移动一次,请你统计有多少敌方的卒处于你的捕获范围内(即,可以被一步捕获的棋子数)。

2 示例描述

2.1 示例 2

【LeetCode】999. 可以被一步捕获的棋子数(C++)
输入:[[".",".",".",".",".",".",".","."],[".",".",".",“p”,".",".",".","."],[".",".",".",“R”,".",".",".",“p”],[".",".",".",".",".",".",".","."],[".",".",".",".",".",".",".","."],[".",".",".",“p”,".",".",".","."],[".",".",".",".",".",".",".","."],[".",".",".",".",".",".",".","."]]
输出:3
解释:
在本例中,车能够捕获所有的卒。

2.2 示例 2

【LeetCode】999. 可以被一步捕获的棋子数(C++)
输入:[[".",".",".",".",".",".",".","."],[".",“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
解释:
象阻止了车捕获任何卒。

2.3 示例 3

【LeetCode】999. 可以被一步捕获的棋子数(C++)
输入:[[".",".",".",".",".",".",".","."],[".",".",".",“p”,".",".",".","."],[".",".",".",“p”,".",".",".","."],[“p”,“p”,".",“R”,".",“p”,“B”,"."],[".",".",".",".",".",".",".","."],[".",".",".",“B”,".",".",".","."],[".",".",".",“p”,".",".",".","."],[".",".",".",".",".",".",".","."]]
输出:3
解释:
车可以捕获位置 b5,d6 和 f5 的卒。

3 解题提示

board.length == board[i].length == 8
board[i][j] 可以是 ‘R’,’.’,‘B’ 或 ‘p’
只有一个格子上存在 board[i][j] == ‘R’

4 解题思路

采用两个数组将步骤叠装,后控制循环走棋。

5 源码详解(C++)

class Solution {
public:
    int numRookCaptures(vector<vector<char>>& board) {
        int n = 0 , x = 0 , y = 0 ;
        int dx[4] = { 0, 1, 0, -1 } ; //控制x方向
        int dy[4] = { 1, 0, -1, 0 } ; //控制y方向
        for ( int i = 0 ; i < 8 ; i ++ )
        {
            for ( int j = 0 ; j < 8 ; j ++ )
            {
                if ( board[i][j] == 'R' )
                {
                    x = i ;
                    y = j ;
                    break ;
                }
            }
        }

        for ( int i = 0 ; i < 4 ; i ++ ) 
        {
            /*
            i = 0 : 向右移动
            i = 1 : 向下移动
            i = 2 : 向左移动
            i = 3 : 向上移动
            */
            for ( int step = 0 ; ; step ++ ) 
            {
                int now_x = x + step * dx[i] ;
                int now_y = y + step * dy[i] ;
                if ( now_x < 0 || now_x >= 8 || now_y < 0 || now_y >= 8 || board[now_x][now_y] == 'B') //出现任意一种情况就退出循环
                {
                    break;
                }
                if ( board[now_x][now_y] == 'p' ) 
                {
                    n ++ ;
                    break ;
                }
            }
        }
        return n ;
    }
};
上一篇:axios框架里面如何使用get,post,通用ajax方法请求。


下一篇:萌新初学java,自己写的剧本,求大佬帮忙纠正下语法上的错误,能让内容更完善些代码量更少些