力扣:999. 可以被一步捕获的棋子数

该代码实现了一个寻找并计算棋盘上车能够捕获的兵数量的方法。在给定的8x8棋盘中,车位于特定位置,代码遍历其上下左右四个方向,遇到兵则计数,遇到王(B)则停止。最终返回车能捕获的兵数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >



/**
 * @author xnl
 * @Description:
 * @date: 2022/7/31   21:41
 */
public class Solution {
    public static void main(String[] args) {
        Solution solution = new Solution();
        char[][] borad = {{'.','.','.','.','.','.','.','.'},{'.','.','.','p','.','.','.','.'},{'.','.','.','R','.','.','.','p'},
                {'.','.','.','.','.','.','.','.'},{'.','.','.','.','.','.','.','.'},
                {'.','.','.','p','.','.','.','.'},{'.','.','.','.','.','.','.','.'},{'.','.','.','.','.','.','.','.'}};
        System.out.println(solution.numRookCaptures(borad));
        

    }

    public int numRookCaptures(char[][] board) {
        int x = 0, y = 0;
        int n = board.length, m = board[0].length;
        out: for (int i = 0; i < n; i++){
            for (int j = 0; j < m; j++){
                if (board[i][j] == 'R'){
                    x = i;
                    y = j;
                    break out;
                }
            }
        }
        int ans = 0;
        int temp = x - 1;
        while (temp >= 0 ){
            if (board[temp][y] == 'p'){
                ans++;
                break;
            } else if (board[temp][y] == 'B'){
                break;
            }
            temp--;
        }

        temp = x + 1;
        while (temp < n ){
            if (board[temp][y] == 'p'){
                ans++;
                break;
            } else if (board[temp][y] == 'B'){
                break;
            }
            temp++;
        }

        temp = y - 1;
        while (temp >= 0 ){
            if (board[x][temp] == 'p'){
                ans++;
                break;
            } else if (board[x][temp] == 'B'){
                break;
            }
            temp--;
        }

        temp = y + 1;
        while (temp < m ){
            if (board[x][temp] == 'p'){
                ans++;
                break;
            } else if (board[x][temp] == 'B'){
                break;
            }
            temp++;
        }
        return ans;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值