【宽度优先】寻找最大价值矿堆

import java.io.*;
import java.util.Arrays;

/**
 * 寻找最大价值矿堆
 */
public class MostValuableMinePile {
    /*
        4 5
        22220
        00000
        00000
        01111
        -----------------
        8
        +++++++++++++++++
        4 5
        22220
        00020
        00010
        01111
        -----------------
        15
     */
    private static final int[][] DIRECTIONS = { {-1, 0}, {1, 0}, {0, -1}, {0, 1} };
    private static final int maxR = 200;
    private static final int maxC = 200;
    private static int[][] matrix = new int[maxR][maxC];
    private static String line;
    private static String[] strArr;
    private static int[] nums;
    private static int rows;
    private static int cols;
    public static void main(String[] args) throws IOException {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
        line = in.readLine();
        strArr = line.split(" ");
        nums = Arrays.stream(strArr).mapToInt(Integer::parseInt).toArray();
        rows = nums[0];
        cols = nums[1];
        for (int i = 0; i < rows; i++) {
            line = in.readLine();
            for (int j = 0; j < cols; j++) {
                matrix[i][j] = Character.getNumericValue(line.charAt(j));
            }
        }

        out.println(mostValuableMinePile());
        out.flush();
        in.close();
        out.close();
    }

    /**
     * 计算矿堆最大价值
     * @return      最大价值矿堆
     */
    public static int mostValuableMinePile() {
        int result = 0;
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                if(matrix[i][j] > 0){
                    int val = countClusterValue(i,j);
                    result = Math.max(result,val);
                }
            }
        }
        return result;
    }

    /**
     * 逐个有效坐标计算矿堆价值
     * @param x     行坐标
     * @param y     列坐标
     * @return      当前区域矿堆价值
     */
    public static int countClusterValue(int x, int y) {
        //坐标越界或已经到了无矿区,则返回0
        boolean invalid = x < 0 || x >= rows || y < 0 || y >= cols || matrix[x][y] == 0;
        if(invalid){
            return 0;
        }
        //取当前坐标价值
        int value = matrix[x][y];
        //当前坐标价值归零,表示已经计算过,下次不再参与计算
        matrix[x][y] = 0;
        //遍历四个方向,递归统计矿堆值
        for (int[] dir:DIRECTIONS) {
            int newX = x + dir[0];
            int newY = y + dir[1];
            value += countClusterValue(newX,newY);
        }
        //返回矿堆总值
        return value;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值