999.能被一步捉到的棋子数(javascript)999.AvailableCapturesforRook
原创在一个 8 x 8 在棋盘上,有一辆白色的汽车(Rook),包含个字符 ‘R’ 表明。棋盘上也可能有空白方块,白色图像(Bishop)和黑马(pawn),分别包含个字符 ‘.’,‘B’ 和 ‘p’ 表明。不难看出,大写字符代表白棋,小写字符代表黑棋。
汽车按照国际象棋的规则移动。从东、西、南和北四个基本方向中选择一个,然后沿所选方向移动,直到满足以下四个条件之一:
- 这位棋手选择自愿停止。
- 棋子停了下来,因为它们到达了棋盘的边缘。
- 棋子移动到某个网格以捕获位于该网格上的敌人(黑色)的棋子,并在该网格中停止。
- 汽车无法进入/与其他友好棋子(白色图像)一起穿过广场,在友好棋子面前停下。
现在,您可以控制汽车移动一次。请计算在你的俘获范围内有多少敌军士兵(即一步可以俘获的碎片数量)。
On an 8 x 8 chessboard, there is exactly one white rook ‘R’ and some number of white bishops ‘B’, black pawns ‘p’, and empty squares ‘.’.
When the rook moves, it chooses one of four cardinal directions (north, east, south, or west), then moves in that direction until it chooses to stop, reaches the edge of the board, captures a black pawn, or is blocked by a white bishop. A rook is considered attacking a pawn if the rook can capture the pawn on the rook’s turn. The number of available captures for the white rook is the number of pawns that the rook is attacking.
Return the number of available captures for the white rook.
示例 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 的卒。
根据问题的含义;白色汽车(R)上,右,下,左,移动
获取当前的白色汽车(R)的位置
1.越界,返回
2.遇到一头白象(B),退回
3.抓住黑爪子(p),数量加一,返回
var numRookCaptures = function (board) {
//买辆白色轿车(R)的位置
let getX, getY
//定义loop,用于退出外循环。
loop:
for (let i = 0; i < 8; i++) {
for (let j = 0; j < 8; j++) {
if (board[i][j] == R) {
getX = i
getY = j
break loop;
}
}
}
let xList = [0, 1, 0, -1]//x向上方向移动0,向右1,向下0,向左-1
let yList = [1, 0, -1, 0]//y向上方向移动1,向右0,向下-1,向左0
let sum = 0//用于存储捕获的典当数量
//四个方向,所以外环是4
for (let i = 0; i < 4; i++) {
for (let j = 0; ; j++) {
//以getX,getY分别作为中心 上、右、下、左1
let xMove = getX + xList[i] * j
let yMove = getY + yList[i] * j
//当移动超出界限,或者遇到一头白象(B),退出内部循环
if (xMove < 0 || xMove >= 8 || yMove < 0 || yMove >= 8 || board[xMove][yMove] == B) {
break
}
//遇到一个黑马(p),sum ++ ,退出内部循环
if (board[xMove][yMove] == p) {
sum++
break
}
}
}
return sum
};
leetcode: https://leetcode.cn/problems/available-captures-for-rook/
版权声明
所有资源都来源于爬虫采集,如有侵权请联系我们,我们将立即删除
itfan123


