经典算法题型之扫雷游戏(二)

解决方案

方法一:深度优先搜索 + 模拟

思路与算法

由于题目要求你根据规则来展示执行一次点击操作后游戏面板的变化,所以我们只要明确该扫雷游戏的规则,并用代码模拟出来即可。

那我们着眼于题目的规则,会发现总共分两种情况:

代码

C++ 实现

复制代码
class Solution {
public:
    int dir_x[8] = {0, 1, 0, -1, 1, 1, -1, -1};
    int dir_y[8] = {1, 0, -1, 0, 1, -1, 1, -1};

    void dfs(vector<vector<char>>& board, int x, int y) {
        int cnt = 0;
        for (int i = 0; i < 8; ++i) {
            int tx = x + dir_x[i];
            int ty = y + dir_y[i];
            if (tx < 0 || tx >= board.size() || ty < 0 || ty >= board[0].size()) {
                continue;
            }
            // 不用判断 M,因为如果有 M 的话游戏已经结束了
            cnt += board[tx][ty] == 'M';
        }
        if (cnt > 0) {
            // 规则 3
            board[x][y] = cnt + '0';
        } else {
            // 规则 2
            board[x][y] = 'B';
            for (int i = 0; i < 8; ++i) {
                int tx = x + dir_x[i];
                int ty = y + dir_y[i];
                // 这里不需要在存在 B 的时候继续扩展,因为 B 之前被点击的时候已经被扩展过了
                if (tx < 0 || tx >= board.size() || ty < 0 || ty >= board[0].size() || board[tx][ty] != 'E') {
                    continue;
                }
                dfs(board, tx, ty);
            }
        }
    }

    vector<vector<char>> updateBoard(vector<vector<char>>& board, vector<int>& click) {
        int x = click[0], y = click[1];
        if (board[x][y] == 'M') {
            // 规则 1
            board[x][y] = 'X';
        } else {
            dfs(board, x, y);
        }
        return board;
    }
};
相关推荐
代码中介商28 分钟前
银行管理系统的业务血肉 —— 流程、状态机、输入校验与持久化(下篇)
c语言·算法
爱编码的小八嘎3 小时前
C语言完美演绎9-12
c语言
Navigator_Z5 小时前
LeetCode //C - 1031. Maximum Sum of Two Non-Overlapping Subarrays
c语言·算法·leetcode
星辰徐哥9 小时前
Unity基础:游戏对象的激活与隐藏:SetActive方法详解
游戏·unity·lucene
leoufung10 小时前
LeetCode 30:Substring with Concatenation of All Words 题解(含 C 语言 uthash 实现)
c语言·leetcode·c#
爱编码的小八嘎10 小时前
C语言完美演绎9-6
c语言
CS创新实验室10 小时前
CS实验室行业报告:游戏行业就业分析报告
大数据·游戏
SunnyByte11 小时前
线性表——单链表的增删查改操作
c语言·单链表
王杨游戏养站系统11 小时前
王杨游戏蜘蛛养站系统:提交百度站长工具平台教程!
游戏·百度·游戏下载站养站系统·游戏养站系统
SunnyByte11 小时前
线性表——双向链表
c语言·链表