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. Win 7打开任务管理器的几种方法

    1. 按住Ctrl和Alt键和Delete键 2. 快速启动栏打开win7任务管理器 3. Ctrl键+Shift键+Esc键的组合键 4. 桌面新建一个文本文档也叫记事本,打开,输入“C:\Wind ...

  2. 报错---“node install.js”

    如图 解决方案: 目录中执行 npm install chromedriver --chromedriver_cdnurl=http://cdn.npm.taobao.org/dist/chromed ...

  3. Jrebel不生效的原因和解决办法

    一.问题原因和解决办法 我这里用的是idea,装了jrebel.之前用的好好的. 后边新建了一个project,不知道为啥,感觉总是不生效,虽然显示class reload了,但感觉还是没起作用. 后 ...

  4. 提交代码到自己的github仓库

    说起来尴尬,好几年前就搞了github建了仓库,当时玩得还有点6,后来一直的公司都是svn,自己业务项目也没玩,都忘了要怎么提交代码到自己的仓库了. 这边再来一波记录吧. 一.配置用户名 git co ...

  5. Elasticsearch笔记(一)—Elasticsearch安装配置

    原文链接:https://my.oschina.net/jhao104/blog/644909 摘要: ElasticSearch是一个基于Lucene的搜索服务器.它提供了一个分布式多用户能力的全文 ...

  6. Windows Server 2008 R2之管理Sysvol文件夹

    以下是Sysvol文件夹示例图 Domain文件夹:是策略的实体,是策略和脚本存放地. Staging Areas:交换区,它用来存放多台DC之间交换(复制)的信息.DC上的相关信息(GPO)首先将要 ...

  7. Centos6.5 虚拟机Mongodb创建副本集

    简单副本集的搭建 官方demo的最小化的副本集为Three Member Sets,一个primary和两个secondary.我们先就搭建一个这样的测试环境. 首先建立三个数据目录和日志目录: cd ...

  8. iOS SwiftMonkey 随机暴力测试

    参考源文章 https://github.com/zalando/SwiftMonkey https://kemchenj.github.io/2017/03/16/2017-03-16/ 简介 这个 ...

  9. ELK之Logstash使用useragent获取浏览器版本、型号以及系统版本

    参考文档:http://www.51niux.com/?id=216    https://www.cnblogs.com/Orgliny/p/5755384.html Logstash中的 logs ...

  10. Git 使用篇二:小组协作开发

    上一片搭建了git远程服务器,那么小组成员在使用git开发的时候都有什么要注意的. 第一步: 首先每个小组成员,在自己本地建立一个目录,作为工作空间,再去git clone 这个远程仓库: git c ...