给出一个boolean类型的二维数组,
只有上下左右可以连接,比如上图改变第三行第二列的布尔值可以使连在一起的true数量最大为10,同数量时优先上然后左,该如何找出该位置
完整算法代码如下:
public class Answer7720122 {
public static void main(String[] args) {
boolean[][] ccMatrix = {
{true, false, true, true},
{true, false, true, false},
{true, false, true, false},
{false, true, false, true},
{false, true, false, true},
{true, false, false, true}};
Map<String, Integer> ijCount = new HashMap<>();
for(int i=0; i<ccMatrix.length; ++i) {
for(int j=0; j<ccMatrix[i].length; ++j) {
if(!ccMatrix[i][j]) {
ccMatrix[i][j] = true;
List<String> tempList = new ArrayList<>();
AtomicInteger count = new AtomicInteger(0);
count(ccMatrix, tempList, count, i, j, 1);
count(ccMatrix, tempList, count, i, j, 2);
count(ccMatrix, tempList, count, i, j, 3);
count(ccMatrix, tempList, count, i, j, 4);
ijCount.put(i+""+j, count.get());
ccMatrix[i][j] = false;
}
}
}
List<Integer> count = ijCount.values().stream().sorted().collect(Collectors.toList());
int max = count.get(count.size()-1);
for(Map.Entry<String, Integer> entry : ijCount.entrySet()) {
if(max == entry.getValue()) {
String key = entry.getKey();
System.out.println("修改第"+key.charAt(0)+"行第"+key.charAt(1)+"列可得到最大为"+max);
}
}
System.out.println("注意:行和列均从0开始计数!");
}
/**
*
* @param arr
* @param tempList
* @param count
* @param i
* @param j
* @param direction 递归方向。1:上左;2:上右;3:下左;4:下右;
*/
private static void count(boolean[][] arr, List<String> tempList, AtomicInteger count, int i, int j, int direction) {
int row = arr.length;
int col = arr[0].length;
if(i<0 || j<0 || i>=row || j>=col) {
return;
}
if(!arr[i][j]) {
return;
}
if(arr[i][j]) {
String key = i+""+j;
if(!tempList.contains(key)) {
tempList.add(key);
count.addAndGet(1);
}
}
switch (direction) {
case 1:
count(arr, tempList, count, i-1, j, direction);
count(arr, tempList, count, i, j-1, direction);
break;
case 2:
count(arr, tempList, count, i-1, j, direction);
count(arr, tempList, count, i, j+1, direction);
break;
case 3:
count(arr, tempList, count, i+1, j, direction);
count(arr, tempList, count, i, j-1, direction);
break;
case 4:
count(arr, tempList, count, i+1, j, direction);
count(arr, tempList, count, i, j+1, direction);
break;
}
}
}
运行结果如下:
修改第2行第1列可得到最大为10
修改第3行第2列可得到最大为10
注意:行和列均从0开始计数!
调试了很久,请采纳,十分感谢!
希望可以额外多加几个鸡腿!