扫雷游戏(洛谷P2670题题解,Java语言描述)

题目要求

P2670题目链接

在这里插入图片描述
在这里插入图片描述

分析

本题可以用作简易版扫雷游戏的核心算法Demo,且很好的考察了一些细节。

我们知道,扫雷的地图里有雷格、空白格、数字格。本题没有空白格,空白格相当于数字0格。

这里可以采用暴力算法,直接建立一个二维数组地图,遍历每个格子,当不是雷的时候再遍历周围的8个格子算出当前的数值。

值得一提的是格子可能在边线上,周围可能不足8个格子,盲目扫描可能越界,导致运行时异常,所以需要进行谨慎的判断。

剩下的也没啥了,我觉得扫雷的话这么暴力的算法还是不算太好,不过也可勉强一用。

AC代码(Java语言描述)

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();
        }
    }
}
  • 6
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

星拱北辰

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值