import java.io.*;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;
/**
* 战场索敌
* 有一个大小是N*M的战场地图,被墙壁#分隔成大小不同的区域,上下左右四个方向相邻的空地‘.’,属于同一个区域
* 只有空地上可能存在敌人E,请求出地图上总共有多少区域里的敌人数小于K
* 行数与列数不超过100
*/
public class CountEnemyNum {
/*
3 5 2
..#EE
E.#E.
###..
------------
1
*/
private static String line;
private static String[] strArr;
private static int[] nums;
private static int rows;
private static int cols;
private static int limit;
private static final int maxR = 100;
private static final int maxC = 100;
private static final int[][] DIRECTIONS = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
private static char[][] field = new char[maxR][maxC];
private static boolean[][] visited = new boolean[maxR][maxC];
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];
limit = nums[2];
for (int i = 0; i < rows; i++) {
line = in.readLine();
char[] chars = line.toCharArray();
if (cols >= 0) {
System.arraycopy(chars, 0, field[i], 0, cols);
}
}
out.println(countEnemyNum());
out.flush();
in.close();
out.close();
}
/**
* 计算安全区域的数量
* @return 地图上总共有多少区域里的敌人数小于limit
*/
public static int countEnemyNum() {
int result = 0;
// 遍历整个战场
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
// 如果这个位置没有被访问过并且不是墙
if (!visited[i][j] && field[i][j] != '#') {
//计算这一区域的敌人
int enemies = bfsCount(i, j);
// 如果这个区域的敌人数量小于limit,则增加安全区域的数量
if (enemies < limit) {
result++;
}
}
}
}
return result;
}
/**
* 使用BFS算法计算一个区域内的敌人数量
* @param x 横坐标
* @param y 纵坐标
* @return 区域内的敌人数量
*/
private static int bfsCount(int x, int y) {
//首先看当前坐标是不是敌人
int enemyCount = field[x][y] == 'E' ? 1 : 0;
//初始化队列
Queue<int[]> queue = new LinkedList<>();
//加入当前坐标
queue.add(new int[]{x, y});
//标记当前坐标已访问过
visited[x][y] = true;
//队列为空时跳出循环
while (!queue.isEmpty()) {
//弹出队列头坐标
int[] current = queue.poll();
// 尝试4个方向
for (int[] dir:DIRECTIONS) {
//新的行坐标
int newRow = current[0] + dir[0];
//新的列坐标
int newCol = current[1] + dir[1];
//检查是否越界,是否已被访问,是否是墙
if (newRow < 0 || newRow >= rows || newCol < 0 || newCol >= cols || visited[newRow][newCol] || field[newRow][newCol] == '#') {
continue;
}
//走到这一步,表示数据合法,先标记访问
visited[newRow][newCol] = true;
//如果发现敌人,增加敌人计数
if (field[newRow][newCol] == 'E') {
enemyCount++;
}
//新坐标加入队列
queue.add(new int[]{newRow, newCol});
}
}
return enemyCount;
}
}
【宽度优先】战场索敌
最新推荐文章于 2024-05-03 16:12:22 发布