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;
}
}
【宽度优先】寻找最大价值矿堆
最新推荐文章于 2024-10-05 22:19:52 发布