作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.cn/


题目地址:https://leetcode.com/problems/minesweeper/description/

题目描述

Let’s play the minesweeper game (Wikipedia, online game)!

You are given a 2D char matrix representing the game board. ‘M’ represents an unrevealed mine, ‘E’ represents an unrevealed empty square, ‘B’ represents a revealed blank square that has no adjacent (above, below, left, right, and all 4 diagonals) mines, digit (‘1’ to ‘8’) represents how many mines are adjacent to this revealed square, and finally ‘X’ represents a revealed mine.

Now given the next click position (row and column indices) among all the unrevealed squares (‘M’ or ‘E’), return the board after revealing this position according to the following rules:

  1. If a mine (‘M’) is revealed, then the game is over - change it to ‘X’.
  2. If an empty square (‘E’) with no adjacent mines is revealed, then change it to revealed blank (‘B’) and all of its adjacent unrevealed squares should be revealed recursively.
  3. If an empty square (‘E’) with at least one adjacent mine is revealed, then change it to a digit (‘1’ to ‘8’) representing the number of adjacent mines.
  4. Return the board when no more squares will be revealed.

Example 1:

  1. Input:
  2. [['E', 'E', 'E', 'E', 'E'],
  3. ['E', 'E', 'M', 'E', 'E'],
  4. ['E', 'E', 'E', 'E', 'E'],
  5. ['E', 'E', 'E', 'E', 'E']]
  6. Click : [3,0]
  7. Output:
  8. [['B', '1', 'E', '1', 'B'],
  9. ['B', '1', 'M', '1', 'B'],
  10. ['B', '1', '1', '1', 'B'],
  11. ['B', 'B', 'B', 'B', 'B']]
  12. Explanation:

Example 2:

  1. Input:
  2. [['B', '1', 'E', '1', 'B'],
  3. ['B', '1', 'M', '1', 'B'],
  4. ['B', '1', '1', '1', 'B'],
  5. ['B', 'B', 'B', 'B', 'B']]
  6. Click : [1,2]
  7. Output:
  8. [['B', '1', 'E', '1', 'B'],
  9. ['B', '1', 'X', '1', 'B'],
  10. ['B', '1', '1', '1', 'B'],
  11. ['B', 'B', 'B', 'B', 'B']]
  12. Explanation:

Note:

  1. The range of the input matrix’s height and width is [1,50].
  2. The click position will only be an unrevealed square (‘M’ or ‘E’), which also means the input board contains at least one clickable square.
  3. The input board won’t be a stage when game is over (some mines have been revealed).
  4. For simplicity, not mentioned rules should be ignored in this problem. For example, you don’t need to reveal all the unrevealed mines when the game is over, consider any cases that you will win the game or flag any squares.

题目大意

给定一个代表游戏板的二维字符矩阵。 ‘M’ 代表一个未挖出的地雷,‘E’ 代表一个未挖出的空方块,‘B’ 代表没有相邻(上,下,左,右,和所有4个对角线)地雷的已挖出的空白方块,数字(‘1’ 到 ‘8’)表示有多少地雷与这块已挖出的方块相邻,‘X’ 则表示一个已挖出的地雷。

现在给出在所有未挖出的方块中(‘M’或者’E’)的下一个点击位置(行和列索引),根据以下规则,返回相应位置被点击后对应的面板:

  1. 如果一个地雷(‘M’)被挖出,游戏就结束了- 把它改为 ‘X’。
  2. 如果一个没有相邻地雷的空方块(‘E’)被挖出,修改它为(‘B’),并且所有和其相邻的方块都应该被递归地揭露。
  3. 如果一个至少与一个地雷相邻的空方块(‘E’)被挖出,修改它为数字(‘1’到’8’),表示相邻地雷的数量。
  4. 如果在此次点击中,若无更多方块可被揭露,则返回面板。

解题方法

DFS

这个题标准的做法就是DFS或者BFS,如果使用DFS则按照题目所说的4种情况依次判断就行。

需要注意的是,如果挖出一个空的方块’E’,那么需要递归所有的相邻方块,即继续调用updateBoard函数,把周围的方块都点一下。

Python代码:

  1. class Solution(object):
  2. def updateBoard(self, board, click):
  3. """
  4. :type board: List[List[str]]
  5. :type click: List[int]
  6. :rtype: List[List[str]]
  7. """
  8. (row, col), directions = click, ((-1, 0), (1, 0), (0, 1), (0, -1), (-1, 1), (-1, -1), (1, 1), (1, -1))
  9. if 0 <= row < len(board) and 0 <= col < len(board[0]):
  10. if board[row][col] == 'M':
  11. board[row][col] = 'X'
  12. elif board[row][col] == 'E':
  13. n = sum([board[row + r][col + c] == 'M' for r, c in directions if 0 <= row + r < len(board) and 0 <= col +c < len(board[0])])
  14. board[row][col] = str(n if n else 'B')
  15. if not n:
  16. for r, c in directions:
  17. self.updateBoard(board, [row + r, col + c])
  18. return board

二刷的C++做法。

  1. class Solution {
  2. public:
  3. vector<vector<char>> updateBoard(vector<vector<char>>& board, vector<int>& click) {
  4. int x = click[0], y = click[1];
  5. const int M = board.size(), N = board[0].size();
  6. if (board[x][y] == 'M') {
  7. board[x][y] = 'X';
  8. } else if (board[x][y] == 'E') {
  9. int mcount = 0;
  10. for (auto p : dirs) {
  11. int nx = x + p.first, ny = y + p.second;
  12. if (nx >= 0 && nx < M && ny >= 0 && ny < N && board[nx][ny] == 'M') {
  13. mcount ++;
  14. }
  15. }
  16. if (mcount > 0) {
  17. board[x][y] = '0' + mcount;
  18. } else {
  19. board[x][y] = 'B';
  20. for (auto p : dirs) {
  21. int nx = x + p.first, ny = y + p.second;
  22. if (nx >= 0 && nx < M && ny >= 0 && ny < N && board[nx][ny] == 'E') {
  23. vector<int> pos = {nx, ny};
  24. updateBoard(board, pos);
  25. }
  26. }
  27. }
  28. }
  29. return board;
  30. }
  31. private:
  32. vector<pair<int, int>> dirs = {{0, 1}, {0, -1}, {1, 1}, {1, 0}, {1, -1}, {-1, 1}, {-1, 0}, {-1, -1}};
  33. };

参考资料:

https://leetcode-cn.com/problems/minesweeper

日期

2018 年 3 月 6 日
2018 年 12 月 15 日 —— 今天四六级

【LeetCode】529. Minesweeper 解题报告(Python & C++)的更多相关文章

  1. LeetCode: Combination Sum 解题报告

    Combination Sum Combination Sum Total Accepted: 25850 Total Submissions: 96391 My Submissions Questi ...

  2. 【LeetCode】94. Binary Tree Inorder Traversal 解题报告(Python&C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 目录 题目描述 解题方法 递归 迭代 日期 题目地址:https://leetcode.c ...

  3. 【LeetCode】Permutations 解题报告

    全排列问题.经常使用的排列生成算法有序数法.字典序法.换位法(Johnson(Johnson-Trotter).轮转法以及Shift cursor cursor* (Gao & Wang)法. ...

  4. LeetCode - Course Schedule 解题报告

    以前从来没有写过解题报告,只是看到大肥羊河delta写过不少.最近想把写博客的节奏给带起来,所以就挑一个比较容易的题目练练手. 原题链接 https://leetcode.com/problems/c ...

  5. LeetCode: Sort Colors 解题报告

    Sort ColorsGiven an array with n objects colored red, white or blue, sort them so that objects of th ...

  6. LN : leetcode 529 Minesweeper

    lc 529 Minesweeper 529 Minesweeper Let's play the minesweeper game! You are given a 2D char matrix r ...

  7. 【LeetCode】107. Binary Tree Level Order Traversal II 解题报告 (Python&C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 方法一:DFS 方法二:迭代 日期 [LeetCode ...

  8. 【LeetCode】206. Reverse Linked List 解题报告(Python&C++&java)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 迭代 递归 日期 [LeetCode] 题目地址:h ...

  9. 【LeetCode】26. Remove Duplicates from Sorted Array 解题报告(Python&C++&Java)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 双指针 日期 [LeetCode] https:// ...

随机推荐

  1. vector初始化的几种方式-STL

     vector<int>::iterator int_ite;  vector<string>::iterator string_ite;  //vector<T> ...

  2. HDFS03 HDFS的API操作

    HDFS的API操作 目录 HDFS的API操作 客户端环境准备 1.下载windows支持的hadoop 2.配置环境变量 3 在IDEA中创建一个Maven工程 HDFS的API实例 用客户端远程 ...

  3. addict, address, adequate.四级

    addict addiction – a biopsychosocial [生物社会心理学的 bio-psycho-social] disorder characterized by persiste ...

  4. 【Go语言学习笔记】包

    包其实是每个大型工程都会使用的模块化工具. 将相关的代码封装成一个包,给其他项目调用,提供不同的功能. GO的设计是将一个文件夹看成一个包,虽然不一定非要用文件夹的名字,但是比较建议. 同一个文件夹下 ...

  5. 强化学习实战 | 表格型Q-Learning玩井字棋(二)

    在 强化学习实战 | 表格型Q-Learning玩井字棋(一)中,我们构建了以Game() 和 Agent() 类为基础的框架,本篇我们要让agent不断对弈,维护Q表格,提升棋力.那么我们先来盘算一 ...

  6. When should we write our own assignment operator in C++?

    The answer is same as Copy Constructor. If a class doesn't contain pointers, then there is no need t ...

  7. Can references refer to invalid location in C++?

    在C++中,引用比指针更加的安全,一方面是因为引用咋定义时必须进行初始化,另一方面是引用一旦被初始化就无法使其与其他对象相关联. 但是,在使用引用的地方仍然会有一些例外. (1)Reference t ...

  8. Ajax请求($.ajax()为例)中data属性传参数的形式

    首先定义一个form表单: <form id="login" > <input name="user" type="text&quo ...

  9. pandas基础学习一

    生成对象 用值列表生成 Series 时,Pandas 默认自动生成整数索引: In [3]: s = pd.Series([1, 3, 5, np.nan, 6, 8]) In [4]: s Out ...

  10. C/C++ Qt 数据库与Chart历史数据展示

    在前面的博文中具体介绍了QChart组件是如何绘制各种通用的二维图形的,本章内容将继续延申一个新的知识点,通过数据库存储某一段时间节点数据的走向,当用户通过编辑框提交查询记录时,程序自动过滤出该时间节 ...