蓝桥杯算法心得——扫雷游戏(BFS)

大家好,我是晴天学长,扫雷也是经典中的经典,这是一个简单的bfs遍历题!💪💪💪


1 )扫雷游戏

在这里插入图片描述


2) .算法思路

扫雷游戏(BFS)
1.接收n,m,用快读接收
2.字符串二维数组s
3.遍历二维数组,用bfs解决
4.输出数组(保存结果数组),如果是0,且接收数组是炸弹,则输出"*"

3).代码示例

package LanQiaoTest.BFS;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Queue;

public class 扫雷游戏 {
    //偏位移
    static int[] dx = {1, -1, 0, 0, 1, -1, 1, -1};
    static int[] dy = {0, 0, 1, -1, 1, 1, -1, -1};

    public static void main(String[] args) throws IOException {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
        String[] s = bufferedReader.readLine().split(" ");
        int n = Integer.parseInt(s[0]);
        int m = Integer.parseInt(s[1]);
        String[][] map = new String[n + 1][m + 1];
        //保存答案
        int[][] result = new int[n+1][m+1];
        //接收数据
        for (int i = 1; i <= n; i++) {
            s = bufferedReader.readLine().split("");
            for (int j = 1; j <= m; j++) {
                map[i][j] = s[j - 1];
            }
        }
        //遍历数据
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= m; j++) {
                if (!(map[i][j].equals("*"))) {
                    //答案
                    int ans = BFS(map, i, j, n, m);
                    result[i][j]=ans;
                }
            }
        }
        //输出数据
        for (int i = 1; i <=n ; i++) {
            for (int j = 1; j <=m ; j++) {
                if (map[i][j].equals("*")){
                    System.out.print("*");
                }
                else {
                    System.out.print(result[i][j]);
                }
            }
            System.out.println();
        }
    }

    private static int BFS(String[][] map, int x, int y, int n, int m) {
        //队列
        Queue<int[]> queue = new LinkedList<>();
        //压入下标
        queue.offer(new int[]{x, y});
        //统计答案
        int ans =0;
        while (!queue.isEmpty()) {
            int[] curr = queue.poll();
            int a = curr[0], b = curr[1];
            for (int i = 0; i < 8; i++) {
                int newx = a + dx[i];
                int newy = b + dy[i];
                if ((newx > 0 && newx <= n)&&(newy>0&&newy<=m)){
                    if (map[newx][newy].equals("*")){
                        ans++;
                    }
                }
            }
        }
        return ans;
    }
}


4).总结

  • BFS模板
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

晴天学长

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

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

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

打赏作者

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

抵扣说明:

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

余额充值