题目来源
题目详情
解析
模拟题,读懂题目是关键。
- 遍历棋盘确定白色车的下标。
- 模拟车移动的规则,朝四个基本方向移动,直到碰到卒或者白色象或者碰到棋盘边缘时停止,用 \textit{cnt}cnt 记录捕获到的卒的数量。
也就是说:
- 循环找到R之后:
- 以R 为原点建立坐标系,依次向上找,向下找,向右找,向左找
int capture_pawn(vector<vector<char>>& board, int x, int y, int dx, int dy){
int cnt = 0;
while (x >= 0 && x < board.size() && y >= 0 && y < board[x].size()){
if(board[x][y] == 'p'){
return 1;
}
if(board[x][y] == 'B'){
return 0;
}
x += dx;
y += dy;
}
return 0;
}
int numRookCaptures(vector<vector<char>>& board) {
for (int i = 0; i < board.size(); ++i) {
for (int j = 0; j < board[i].size(); ++j) {
if(board[i][j] == 'R'){
return
capture_pawn(board, i, j, 0, 1) +
capture_pawn(board, i, j, 0, -1) +
capture_pawn(board, i, j, -1, 0) +
capture_pawn(board, i, j, 1, 0) ;
}
}
}
return -1;
}
public static int numRookCaptures(char[][] board) {
int count = 0;
for (int i = 0; i < board.length; i++){
for (int j = 0; j < board[i].length; j++){
if (board[i][j] == 'R'){
//以R 为原点建立坐标系
//依次向上找,向下找,向右找,向左找
return cap(board, i, j, 0, 1) + cap(board, i, j, 0, -1) + cap(board, i, j, -1, 0) + cap(board, i, j, 1, 0);
}
}
}
return count;
}
public static int cap(char[][] board, int x, int y, int dx, int dy){
while (x > -1 && x < board.length && y > -1 && y < board[x].length && board[x][y] != 'B'){
if (board[x][y] == 'p'){
return 1;
}
x = x + dx;
y = y + dy;
}
return 0;
}
public static void main(String[] args) {
char [][] boadr = new char[][]{{'.','.','.','.','.','.','.','.'},
{'.','.','.','p','.','.','.','.'},
{'.','.','.','R','.','.','.','p'},
{'.','.','.','.','.','.','.','.'},
{'.','.','.','.','.','.','.','.'},
{'.','.','.','p','.','.','.','.'},
{'.','.','.','.','.','.','.','.'},
{'.','.','.','.','.','.','.','.'}};
System.out.println(numRookCaptures(boadr));
}