题目
思路
1.dfs深度遍历
2、若某个位置未被搜索过并且不是城墙“#”,那么可以开始DFS遍历,单个源头的搜索区域,该区域的‘E’(敌军)数量+1.遍历完成后,对总敌军数量<K,总结过+1.
代码
import java.util.Scanner;
public class Main {
public static int[][] direction = { { -1, 0 }, { 1, 0 }, { 0, -1 }, { 0, 1 } };
// 创建二维数组,记录map是否被访问
public static boolean[][] visited_info = new boolean[100][100];
public static void main(String[] args) {
// 处理输入
Scanner input = new Scanner(System.in);
int N = input.nextInt();
int M = input.nextInt();
int K = input.nextInt();
input.nextLine();// 接收“\n”换行符号
String[][] arr_map = new String[N][M];
for (int i = 0; i < N; i++) {
String strs = input.nextLine();
for (int j = 0; j < M; j++) {
arr_map[i][j] = strs.substring(j, j + 1);
}
}
// for(int i = 0;i < arr_map.length;i++){
// for(int j = 0;j < arr_map[i].length;j++){
// System.out.print(arr_map[i][j] + " ");
// }
// System.out.println();
// }
System.out.println(dfs(arr_map, K));
}
public static int dfs(String[][] arr_map, int target) {
int sumCount = 0;
for (int i = 0; i < arr_map.length; i++) {
for (int j = 0; j < arr_map[i].length; j++) {
int count = dfs(arr_map, visited_info, i, j);
//判断区域内敌人数量是否
if (count > 0 && count < target) {
sumCount++;
System.out.println("sumCount = " + sumCount);
}
}
}
return sumCount;
}
public static int dfs(String[][] arr_map, boolean[][] visited_info, int i, int j) {
int count = 0;
if (arr_map[i][j].equals("#")) {// 注意使用equals()
return count;
}
if (isVisited(i, j)) {
return count;
}
visited_info[i][j] = true;// 置为true
if (arr_map[i][j].equals("E")) {
count++;
}
for (int d = 0; d < 4; d++) {
int new_x = i + direction[d][0];
int new_y = j + direction[d][1];
// 如果新位置在区域内并且不是城墙,而且没有被访问过,进行DFS,返回count
if (new_x >= 0 && new_x < arr_map.length && new_y >= 0 && new_y < arr_map[new_x].length
&& (!arr_map[new_x][new_y].equals("#")) && (!isVisited(new_x, new_y))) {
count += dfs(arr_map, visited_info, new_x, new_y);
}
}
return count;
}
// 判断是否被访问过
public static boolean isVisited(int i, int j) {
if (visited_info[i][j]) {
return true;
}
return false;
}
}