# 题目：

board.length == board[i].length == 8
board[i][j] 可以是 ‘R’，’.’，‘B’ 或 ‘p’

# 解法：

// Solution One -- 传统4个while
/**
* @param {character[][]} board
* @return {number}
*/
// 60ms 33.8mb
var numRookCaptures0 = function(board) {
let m = 0, n = 0, count = 0
// 先找到R的位置
for(let i = 0; i < 8; i++){
for(let j = 0; j < 8; j++){
if(board[i][j] === 'R'){
m = i
n = j
// 开始判断四个方向能收录的个数
// 上
while(n >= 0) {
if(board[i][n] == 'p'){
count += 1
break
}else if(board[i][n] == 'B'){
break
}
n--
}
// 下
n = j
while(n < 8) {
if(board[i][n] == 'p'){
count += 1
break
}else if(board[i][n] == 'B'){
break
}
n++
}
// 左
while(m >= 0) {
if(board[m][j] == 'p'){
count += 1
break
}else if(board[m][j] == 'B'){
break
}
m--
}
// 右
m = i
while(m < 8) {
if(board[m][j] == 'p'){
count += 1
break
}else if(board[m][j] == 'B'){
break
}
m++
}
break // 一定break
}
}
}
return count
};

// Solution Two  --  方向数组
// 64ms 33.9mb
var numRookCaptures1 = function(board){
let count = 0, m = 0, n = 0
const dx = [0, 1, 0, -1], dy = [1, 0, -1, 0]
for(let i = 0; i < 8; i++){
for(let j = 0; j< 8; j++){
if(board[i][j] === 'R'){
m = i
n = j
break
}
}
}
// 4 -> 4个方向
for(let i = 0; i < 4; i++){
for(let step = 0; ; step ++){
let tx = m + step * dx[i],
ty = n + step * dy[i]
if(tx < 0 || tx >= 8 || ty < 0 || ty >= 8 || board[tx][ty] === 'B') break
if(board[tx][ty] === 'p'){
count++
break
}
}
}
return count
}


©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客