Let's play the minesweeper game (Wikipediaonline 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:

Input: 

[['E', 'E', 'E', 'E', 'E'],
['E', 'E', 'M', 'E', 'E'],
['E', 'E', 'E', 'E', 'E'],
['E', 'E', 'E', 'E', 'E']] Click : [3,0] Output: [['B', '1', 'E', '1', 'B'],
['B', '1', 'M', '1', 'B'],
['B', '1', '1', '1', 'B'],
['B', 'B', 'B', 'B', 'B']] Explanation:

Example 2:

Input: 

[['B', '1', 'E', '1', 'B'],
['B', '1', 'M', '1', 'B'],
['B', '1', '1', '1', 'B'],
['B', 'B', 'B', 'B', 'B']] Click : [1,2] Output: [['B', '1', 'E', '1', 'B'],
['B', '1', 'X', '1', 'B'],
['B', '1', '1', '1', 'B'],
['B', 'B', 'B', 'B', 'B']] 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.

这一题乍一看好像蛮复杂的, 但实际上就是BFS, 只不过要注意的就是如果检测的点的周围有mine, 不需要将neighbor 再append进入queue, 因为根据规则2 和3 可知不需要recursive去继续, 其他的就是常规的BFS的操作, 然后看了discussion之后, 发现可以将其中部分code简化为一行, python果然是简洁的语言!

1. constraints

1) matrix [1,50] * [1, 50], cannot be empty

2) click will be 'M' or 'E', always valid

3) no 'X' at beginning.

2. ideas

BFS:   T: O(m*n)   S: O(m*n) # even we change in place, but we still need space for queue.

1, if click == 'M', change into "X" , return board

2. queue(init:[(orir, oric)]), visited(inti: set((orir, oric))), dirs

3. queue.popleft(), check neighbors , count number of 'M', if >0, change into str(count), else "B" and queue.append(neigb) if neigb == 'E' and not visited

4. return board

3. code 1 class Solution:

     def Mine(self, board, click):
lr, lc , orir, oric = len(board), len(board[0]), click[0], click[-1]
if board[orir][oric] == 'M':
board[orir][oric] = 'X'
return board
queue, visited, dirs = collections.deque([(orir, oric)]), set((orir, oric)), [(0,1), (0,-1), (-1,0), (-1,-1), (-1,1), (1, -1), (1,0), (1,1)]
while queue:
pr, pc = queue.popleft()
count = 0
# visited.add((pr,pc)) # 不在这里加是因为会time limit 不符合, 因为还是会有重复的加入情况, 因为不仅仅是上下左右,neib和之前的node只有一个connection, 现在有多个connection
for d1, d2 in dirs:
nr, nc = pr + d1, pc + d2
if 0<= nr < lr and 0<= nc < lc:
if board[nr][nc] == 'M':
count += 1
if count == 0:
board[pr][pc] = 'B'
for d1, d2 in dirs:
nr, nc = pr + d1, pc + d2
if 0<= nr < lr and 0<= nc < lc:
if board[nr][nc] == 'E' and (nr, nc) not in visited:
queue.append((nr, nc))
visited.add((nr, nc)) # 所以visited加在这, 自行体会...
return board

3.2  updated code(更简洁)

 lr, lc, orir, oric = len(board), len(board[0]), click[0], click[-1]
if board[orir][oric] == 'M':
board[orir][oric] = 'X'
return board
queue, visited, dirs = collections.deque([(orir,oric)]), set((orir, oric)), [(0,1), (0,-1), (-1,0), (-1,-1), (-1,1), (1, -1), (1,0), (1,1)]
while queue:
pr, pc = queue.popleft()
#visited.add((pr,pc))
count = sum(board[pr + d1][pc + d2] == 'M' for d1, d2 in dirs if 0 <= pr + d1 <lr and 0 <= pc + d2< lc)
board[pr][pc] = 'B' if count == 0 else str(count)
if count == 0:
for d1, d2 in dirs:
nr, nc = pr + d1, pc + d2
if 0 <= nr <lr and 0 <= nc < lc and board[nr][nc] == 'E' and (nr, nc) not in visited:
queue.append((nr,nc))
visited.add((nr, nc))
return board

3.3 DFS, 但是本质一样.

 # DFS   T: O(m*n)  S: O(m*n)   # only difference between DFS and BFS is one use stack , the other use deque. so to the 2D array if can use DFS, usually can use BFS too.
lr, lc, orir, oric = len(board), len(board[0]), click[0], click[-1]
if board[orir][oric] == 'M':
board[orir][oric] = 'X'
return board
stack, visited, dirs = [(orir, oric)], set((orir, oric)), [(0,1), (0, -1), (1, -1), (1, 0), (1,1), (-1, -1), (-1, 0), (-1, 1)]
while stack:
pr, pc = stack.pop()
count = sum(board[pr + d1][pc + d2]== 'M' for d1, d2 in dirs if 0<= pr+d1 < lr and 0<= pc + d2 < lc)
if count > 0:
board[pr][pc] = str(count)
else:
board[pr][pc] = 'B'
for d1, d2 in dirs:
nr, nc = pr + d1, pc + d2
if 0 <= nr < lr and 0 <= nc < lc and board[nr][nc] == 'E' and (nr, nc) not in visited:
stack.append((nr, nc))
visited.add((nr, nc))
return board

4. test cases

题目上的两个cases

[LeetCode] 529. Minesweeper_ Medium_ tag: BFS的更多相关文章

  1. [LeetCode] 490. The Maze_Medium tag: BFS/DFS

    There is a ball in a maze with empty spaces and walls. The ball can go through empty spaces by rolli ...

  2. [LeetCode] 207 Course Schedule_Medium tag: BFS, DFS

    There are a total of n courses you have to take, labeled from 0 to n-1. Some courses may have prereq ...

  3. [LeetCode] 733. Flood Fill_Easy tag: BFS

    An image is represented by a 2-D array of integers, each integer representing the pixel value of the ...

  4. [LeetCode] 690. Employee Importance_Easy tag: BFS

    You are given a data structure of employee information, which includes the employee's unique id, his ...

  5. [LeetCode] 130. Surrounded Regions_Medium tag: DFS/BFS

    Given a 2D board containing 'X' and 'O' (the letter O), capture all regions surrounded by 'X'. A reg ...

  6. [LeetCode] 849. Maximize Distance to Closest Person_Easy tag: BFS

    In a row of seats, 1 represents a person sitting in that seat, and 0 represents that the seat is emp ...

  7. [LeetCode] 513. Find Bottom Left Tree Value_ Medium tag: BFS

    Given a binary tree, find the leftmost value in the last row of the tree. Example 1: Input: 2 / \ 1 ...

  8. [LeetCode] 821. Shortest Distance to a Character_Easy tag: BFS

    Given a string S and a character C, return an array of integers representing the shortest distance f ...

  9. Leetcode之广度优先搜索(BFS)专题-529. 扫雷游戏(Minesweeper)

    Leetcode之广度优先搜索(BFS)专题-529. 扫雷游戏(Minesweeper) BFS入门详解:Leetcode之广度优先搜索(BFS)专题-429. N叉树的层序遍历(N-ary Tre ...

随机推荐

  1. HDFS的客户端操作

    命令行操作: -help      功能:输出这个命令参数手册 -ls                   功能:显示目录信息 示例: hadoop fs -ls hdfs://hadoop-serv ...

  2. C#设计模式--装饰器模式

    0.C#设计模式-简单工厂模式 1.C#设计模式--工厂方法模式 2.C#设计模式--抽象工厂模式 3.C#设计模式--单例模式 4.C#设计模式--建造者模式 5.C#设计模式--原型模式 6.C# ...

  3. Android 反编译Apk提取XML文件

    Apktool https://ibotpeaches.github.io/Apktool/install/ 下载地址:Apktool https://bitbucket.org/iBotPeache ...

  4. minix中二分查找bsearch的实现

    在看minix中bsearch实现的源代码之前,先学习一下C 语言中void类型以及void*类型的使用方法与技巧. void的含义: void的字面意思是“无类型”,void *则为“无类型指针”, ...

  5. Setting up Unicorn with Nginx

    gem install unicorn or gem 'unciron' 1 install Nginx yum install ... 2 Configuration vi /etc/nginx/n ...

  6. 关于在Linux下apache-maven的安装

    本文所涉及到的软件如下:jdk版本号:1.7.0_45apache-maven版本号:3.1.1 apache-maven的安装过程如下: apache-maven的官方网址:http://maven ...

  7. iOS中self.xxx 和 _xxx 下划线的区别

    property (nonatomic,copy) NSString *propertyName; self.propertyName 是对属性的拜访: _propertyName 是对部分变量的拜访 ...

  8. React 事件处理函数

    触摸事件:onTouchCancel\onTouchEnd\onTouchMove\onTouchStart (只会在移动设备上接受) 键盘事件:onKeyDown\onKeyPress\onKeyU ...

  9. AD初体验

    首先是因为想用51做个小项目,所以想到不如成这个机会把AD学一下吧,老师说我们这个专业无论画图还是电路设计都得精通,想想自己还是能力欠缺,到大三了才开始学习绘制 原理图. 好了废话不说,下面说说我的第 ...

  10. Java--static、final、static final的区别

    一.final final修饰类:表示该类不能被继承:final类中的方法默认是final的: final修饰方法:表示该方法无法被重写: final修饰方法参数:表示在变量的生存期中它的值不能被改变 ...