999. Available Captures for Rook

#999. Available Captures for Rook

On an 8 x 8 chessboard, there is one white rook. There also may be empty squares, white bishops, and black pawns. These are given as characters ‘R’, ‘.’, ‘B’, and ‘p’ respectively. Uppercase characters represent white pieces, and lowercase characters represent black pieces.
The rook moves as in the rules of Chess: it chooses one of four cardinal directions (north, east, west, and south), then moves in that direction until it chooses to stop, reaches the edge of the board, or captures an opposite colored pawn by moving to the same square it occupies. Also, rooks cannot move into the same square as other friendly bishops.
Return the number of pawns the rook can capture in one move.

在这里插入图片描述
这道题我读了好多好多遍,才读懂…其实很简单,问的是在R只走一步的情况下,有几种可能可以吃掉p,且如果R和p之间有B,也不能吃的。…所以就按照上下左右四种情况分类讨论。

/**
 * @param {character[][]} board
 * @return {number}
 */
var numRookCaptures = function(board) {
    var row=0;
    var col=0;
    var result=0;
    for(let i=0;i<board.length;i++) {
        for(let j=0;j<board.length;j++) {
            if(board[i][j]==='R') {
                row=i;
                col=j;
                break;
            }
        }
    }
    
    for(let i=row-1;i>=0;i--) {
        if(board[i][col]==='p') {
            result++;
            break;
        }
        if(board[i][col]==='B') {
            break;
        }
    }
    for(let i=row+1;i<board.length;i++) {
        if(board[i][col]==='p') {
            result++;
            break;
        }
        if(board[i][col]==='B') {
            break;
        }
    }
    for(let i=col-1;i>=0;i--) {
        if(board[row][i]==='p') {
            result++;
            break;
        }
        if(board[row][i]==='B') {
            break;
        }
    }
    for(let i=col+1;i<board[row].length;i++) {
        if(board[row][i]==='p') {
            result++;
            break;
        }
        if(board[row][i]==='B') {
            break;
        }
    }
    return result;
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值