描述
小李很喜欢玩泡泡堂,在泡泡堂里的炸弹范围都是十字范围,但他玩的很菜每次都会被炸弹炸到,他很不甘心。于是,他打算写一个程序帮他找到会被炸弹波及的区域。在程序里他自己指定扫雷区域的大小(数组),炸弹位置(用同一字符表示)和其他位置(用同一字符表示)。有重合的算一个,如果全是炸弹没有其他区域算0。
输入描述
第一行输入区域的宽(n)和长(m),炸弹字符(a),其他区域字符(b)
接下来的n*m行表示地图区域炸弹和安全区的分布情况
输出描述
炸弹波及到的区域数量
#include <stdio.h>
#include <stdlib.h>
//判断该单元是否为有效单元
int is_valid(int row, int col, int n, int m) {
return row >= 0 && row < n && col >= 0 && col < m;
}
int count_affected(char **map, char **visited, int n, int m, char bomb, char other) {
int count = 0;
//用于调整上下左右的数组
int directions[4][2] = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (map[i][j] == bomb && !visited[i][j]) {
for (int k = 0; k < 4; k++) {
int new_row = i + directions[k][0];
int new_col = j + directions[k][1];
//判断是否是目标位置
if (is_valid(new_row, new_col, n, m) && map[new_row][new_col] == other && visited[new_row][new_col] ==0) {
count++;
visited[new_row][new_col] = 1;
}
}
}
}
}
return count;
}
int main() {
int n, m;
char bomb, other;
scanf("%d %d %c %c", &n, &m, &bomb, &other);
//动态分配模拟二维数组,避免编译器出错
char **map = (char **)malloc(n * sizeof(char *));
char **visited = (char **)malloc(n * sizeof(char *));
for (int i = 0; i < n; i++) {
map[i] = (char *)malloc(m * sizeof(char));
visited[i] = (char *)malloc(m * sizeof(char));
for (int j = 0; j < m; j++) {
visited[i][j] = 0;
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
scanf(" %c", &map[i][j]);
}
}
int affected = count_affected(map, visited, n, m, bomb, other);
printf("%d\n", affected);
for (int i = 0; i < n; i++) {
free(map[i]);
free(visited[i]);
}
free(map);
free(visited);
return 0;
}