题目:
在一个 8 x 8 的棋盘上,有一个白色车(rook)。也可能有空方块,白色的象(bishop)和黑色的卒(pawn)。它们分别以字符 “R”,“.”,“B” 和 “p” 给出。大写字符表示白棋,小写字符表示黑棋。
车按国际象棋中的规则移动:它选择四个基本方向中的一个(北,东,西和南),然后朝那个方向移动,直到它选择停止、到达棋盘的边缘或移动到同一方格来捕获该方格上颜色相反的卒。另外,车不能与其他友方(白色)象进入同一个方格。
返回车能够在一次移动中捕获到的卒的数量。
示例:
示例 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 的卒。
提示:
board.length == board[i].length == 8
board[i][j] 可以是 'R','.','B' 或 'p'
只有一个格子上存在 board[i][j] == 'R'
解题思路:
(1)先遍历找到白色车;
(2)再以白色车所在位置,分别向四个方向移动:
a、如果遇到 . (表示空格)就可以继续朝同一个方向前进,直到不能再走为止(到达边缘);
b、如果遇到 B (白色的象)就停止找,因为车不能与其他友方(白色)象进入同一个方格;
c、如果遇到 p(黑色的卒) 说明找到了,停止,计数加一。
代码实现:
class Solution {
public int numRookCaptures(char[][] board) {
int col = board.length;
int row = board[0].length;
int m=0,n=0;
int count = 0;
int[] dx = {0,1,0,-1};
int[] dy = {1,0,-1,0};
for(int i=0;i<col;i++){
for(int j=0;j<row;j++){
if(board[i][j] == 'R'){
m = i;
n = j;
}
}
}
//分别从四个方向遍历判断
for(int i=0;i<4;i++){
int tx = m,ty = n;
while(true){
tx += dx[i];
ty += 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;
}
}
复杂度分析
- 时间复杂度:O(n^2),其中 n 是棋盘的边长。找白色车在棋盘中的位置需要 O(n^2) 的时间复杂度,模拟车在四个方向上捕 获颜色相反的卒需要 O(n) 的时间复杂度,所以一共需要 O(n^2+n) = O(n^2) 的时间复杂度。
- 空间复杂度:O(1),只需要常数空间存放若干变量。