[LeetCode]999. 可以被一步捕获的棋子数
- 可以被一步捕获的棋子数
简单
给定一个 8 x 8 的棋盘,只有一个 白色的车,用字符 '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 的卒。
class Solution {
public:
int numRookCaptures(vector<vector<char>>& board) {
//首先只有一个白色车为'R',另有白色象'B',和黑色卒'p' 空方块为'.'.棋盘为8*8.首先找到车'r'的位置,然后判断车的四个方向内第一个非空白块和边界的位置的棋子是否为卒。若为卒则加1
if(!board.size())
return 0;
if(!board[0].size())
return 0;
int rooks_position_i=0;
int rooks_position_j=0;
int Pieces_count=0;
for(unsigned int i=0;i<board.size();i++){
for(unsigned int j=0;j<board[0].size();j++){//行数为高
if(board[i][j]=='R'){
rooks_position_i=i;
rooks_position_j=j;
// printf("i:%d,j:%d/n",i,j);
break;
}
}
}
for( int j=rooks_position_j+1;j<board[rooks_position_i].size();j++){//行数为高j遍历
if(board[rooks_position_i][j]!='.'){
if(board[rooks_position_i][j]=='p'){
// printf("rooks_position_i:%d,j:%d/n",rooks_position_i, j);
Pieces_count++;
break;
}
else
break;
}
}
if(rooks_position_j>0)
for( int j=rooks_position_j-1;j>=0;j--){//行数为高j遍历
if(board[rooks_position_i][j]!='.'){
if(board[rooks_position_i][j]=='p'){
// printf("rooks_position_i:%d,j:%d/n",rooks_position_i, j);
Pieces_count++;
break;
}
else
break;
}
}
if(rooks_position_i>0)
for( int i=rooks_position_i-1;i>=0;i--){//列数为宽i遍历
if(board[i][rooks_position_j]!='.')
{
if(board[i][rooks_position_j]=='p'){
// printf("rooks_position_j:%d,i:%d/n",rooks_position_j, i);
Pieces_count++;
break;
}
else
break;
}
}
for( int i=rooks_position_i+1;i<board.size();i++){////列数为宽i遍历
if(board[i][rooks_position_j]!='.'){
if(board[i][rooks_position_j]=='p'){
// printf("rooks_position_j:%d,i:%d/n",rooks_position_j, i);
Pieces_count++;
break;
}
else
break;
}
}
return Pieces_count;
}
};
posted on 2024-08-24 15:50 Mo_Jianjun 阅读(5) 评论(0) 编辑 收藏 举报