题解 | 扫雷
扫雷
https://www.nowcoder.com/practice/d5f277427d9a4cd3ae60ea6c276dddfd
import java.util.Scanner;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int m = in.nextInt();
//吸收换行
in.nextLine();
//定义最初的字符数组
char[][]arr = new char[n][m];
//将读取到的字符串转为字符形式 并存入字符数组1
for (int i = 0; i < n; i++) {
String line = in.nextLine();
arr[i] = line.toCharArray();
}
//八个方向的位置
int dx[] = {-1, -1, -1, 0, 0, 1, 1, 1};
int dy[] = {-1, 0, 1, -1, 1, -1, 0, 1};
//重新搞个字符数组2,用来接收一个一个判断之后的字符数组状态
//通过调取字符数组1 判断有雷 或者周围雷的个数
char[][]ans = new char[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (arr[i][j] == '*') {
ans[i][j] = '*';
} else {
//数 字符数组arr[i][j]周围雷的个数 判断是否在数组范围内 判断8个方向雷的情况
int count = 0;
//八个方向
for (int k = 0; k < 8; k++) {
int x = i + dx[k];
int y = j + dy[k];
if (x >= 0 && x < n && y >= 0 && y < m) {
if (arr[x][y] == '*')
count++;
}
}
//count 是数字,直接强转 (char) 会变成奇怪符号
//加 '0' 就是把数字翻译成屏幕上能看到的数字字符
ans[i][j] = (char)('0'+count);
}
}
}
for (int i = 0; i < n; i++) {
System.out.println(ans[i]);
}
}
}