P2670题目链接
本题可以用作简易版扫雷游戏的核心算法Demo,且很好的考察了一些细节。
我们知道,扫雷的地图里有雷格、空白格、数字格。本题没有空白格,空白格相当于数字0格。
这里可以采用暴力算法,直接建立一个二维数组地图,遍历每个格子,当不是雷的时候再遍历周围的8个格子算出当前的数值。
值得一提的是格子可能在边线上,周围可能不足8个格子,盲目扫描可能越界,导致运行时异常,所以需要进行谨慎的判断。
剩下的也没啥了,我觉得扫雷的话这么暴力的算法还是不算太好,不过也可勉强一用。
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int column = scanner.nextInt(), row = scanner.nextInt();
scanner.nextLine();
char[][] graph = new char[column][row];
for (int i = 0; i < column; i++) {
char[] temp = scanner.nextLine().toCharArray();
for (int j = 0; j < row; j++) {
graph[i][j] = temp[j];
}
}
scanner.close();
for (int i = 0; i < column; i++) {
for (int j = 0; j < row; j++) {
char temp = graph[i][j];
if (temp == '*') {
continue;
}
char tempNum = '0';
if (i - 1 >= 0) {
if (graph[i-1][j] == '*') {
tempNum++;
}
if (j - 1 >= 0 && graph[i-1][j-1] == '*') {
tempNum++;
}
if (j + 1 < row && graph[i-1][j+1] == '*') {
tempNum++;
}
}
if (i + 1 < column) {
if (graph[i+1][j] == '*') {
tempNum++;
}
if (j - 1 >= 0 && graph[i+1][j-1] == '*') {
tempNum++;
}
if (j + 1 < row && graph[i+1][j+1] == '*') {
tempNum++;
}
}
if (j - 1 >= 0 && graph[i][j-1] == '*') {
tempNum++;
}
if (j + 1 < row && graph[i][j+1] == '*') {
tempNum++;
}
graph[i][j] = tempNum;
}
for (int j = 0; j < row; j++) {
System.out.print(graph[i][j]);
}
System.out.println();
}
}
}