您现在的位置是:主页 > news > 龙口网站制作价格/搜索引擎的使用方法和技巧
龙口网站制作价格/搜索引擎的使用方法和技巧
admin2025/4/25 15:41:39【news】
简介龙口网站制作价格,搜索引擎的使用方法和技巧,宁波广告公司网站建设,手机浏览器网页加速器529.扫雷游戏 让我们一起来玩扫雷游戏! 给定一个代表游戏板的二维字符矩阵。 ‘M’ 代表一个未挖出的地雷,‘E’ 代表一个未挖出的空方块,‘B’ 代表没有相邻(上,下,左,右,和所有4…
龙口网站制作价格,搜索引擎的使用方法和技巧,宁波广告公司网站建设,手机浏览器网页加速器529.扫雷游戏
让我们一起来玩扫雷游戏!
给定一个代表游戏板的二维字符矩阵。 ‘M’ 代表一个未挖出的地雷,‘E’ 代表一个未挖出的空方块,‘B’ 代表没有相邻(上,下,左,右,和所有4…
529.扫雷游戏
让我们一起来玩扫雷游戏!
给定一个代表游戏板的二维字符矩阵。 ‘M’ 代表一个未挖出的地雷,‘E’ 代表一个未挖出的空方块,‘B’ 代表没有相邻(上,下,左,右,和所有4个对角线)地雷的已挖出的空白方块,数字(‘1’ 到 ‘8’)表示有多少地雷与这块已挖出的方块相邻,‘X’ 则表示一个已挖出的地雷。
现在给出在所有未挖出的方块中(‘M’或者’E’)的下一个点击位置(行和列索引),根据以下规则,返回相应位置被点击后对应的面板:
如果一个地雷(‘M’)被挖出,游戏就结束了- 把它改为 ‘X’。
如果一个没有相邻地雷的空方块(‘E’)被挖出,修改它为(‘B’),并且所有和其相邻的未挖出方块都应该被递归地揭露。
如果一个至少与一个地雷相邻的空方块(‘E’)被挖出,修改它为数字(‘1’到’8’),表示相邻地雷的数量。
如果在此次点击中,若无更多方块可被揭露,则返回面板。
思路
DFS
看到这种题就想到了DFS和BFS,注意理解游戏规则即可,只有周围都没有雷时,才能递归揭露,如果有雷就只处理当前块即可。
代码
class Solution {
public:int dx[8] = {-1, -1, -1, 0, 0, 1, 1, 1};int dy[8] = {-1, 0, 1, -1, 1, -1, 0, 1};void dfs(vector<vector<char>>& board, int x, int y) {int num = 0;//检查周围雷for(int i = 0; i < 8; i++) {int next_x = x + dx[i], next_y = y + dy[i];if(next_x >= 0 && next_x < board.size() && next_y >= 0 && next_y < board[0].size() && board[next_x][next_y] == 'M') {++num;}}//没雷可以递归揭露if(num == 0) {board[x][y] = 'B';for(int i = 0; i < 8; i++) {int next_x = x + dx[i], next_y = y + dy[i];if(next_x >= 0 && next_x < board.size() && next_y >= 0 && next_y < board[0].size() && board[next_x][next_y] == 'E') {dfs(board, next_x, next_y);}}}//有雷只能处理当前else {board[x][y] = num + '0';}}vector<vector<char>> updateBoard(vector<vector<char>>& board, vector<int>& click) {int x = click[0], y = click[1];if(board[x][y] == 'M') {board[x][y] = 'X';}else {dfs(board, x, y);}return board;}
};
BFS
BFS需要借助到一个队列以及一个访问数组记录当前点是否被处理过。
代码
class Solution {
public:int dx[8] = {-1, -1, -1, 0, 0, 1, 1, 1};int dy[8] = {-1, 0, 1, -1, 1, -1, 0, 1};vector<vector<char>> updateBoard(vector<vector<char>>& board, vector<int>& click) {int m = board.size();int n = board[0].size();int x = click[0], y = click[1];if(board[x][y] == 'M') {board[x][y] = 'X';return board;}//访问数组vector<vector<bool>> visited(m, vector<bool>(n, false));queue<pair<int, int>> q;q.push({x, y});visited[x][y] = true;while(!q.empty()) {pair<int, int> tmp = q.front();q.pop();int ans = 0;int x1 = tmp.first, y1 = tmp.second;//查看周围雷for(int i = 0; i < 8; i++) {int next_x = x1 + dx[i];int next_y = y1 + dy[i];if(next_x >= 0 && next_x < m && next_y >= 0 && next_y < n && board[next_x][next_y] == 'M') {ans++;}}//处理没雷情况if(ans == 0) {board[x1][y1] = 'B';for(int i = 0; i < 8; i++) {int next_x = x1 + dx[i];int next_y = y1 + dy[i];if(next_x >= 0 && next_x < m && next_y >= 0 && next_y < n && board[next_x][next_y] == 'E' && visited[next_x][next_y] == false) {q.push({next_x, next_y});visited[next_x][next_y] = true;}}}//有雷情况else {board[x1][y1] = ans + '0';}}return board;}
};