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. Dropbox 在 Ubuntu 上需要认证授权的问题

    在 Ubuntu 上,通过 Ubuntu软件中心 搜索下载安装了 Dropbox . 运行时,弹出如下图的提示. 输入密码,点击 授权 后,没有出现 Dropbox 的运行界面. 再次点击运行,仍会出 ...

  2. SharpGL学习笔记(二) 模型变换(几何变换)

    (二) 模型变换 模形变换就是指的在世界坐标系中(world space)做“移动”,“旋转", "缩放"三种操作. 首先要说明的,在Opengl中,是用4x4矩阵进行坐 ...

  3. c实现的list

    // clist.cpp : 定义控制台应用程序的入口点.// #include "stdafx.h"#include <stdio.h>#include <ma ...

  4. XCode 遇到的问题

    俗话说:工欲善其事必先利其器.抛弃了VS,投入XCode的怀抱.先不说两者的差距,还是先熟悉开发工具是关键.下面列出个人使用中遇到的一些问题. Problem1:修改Xcode字体颜色以及调整字体大小 ...

  5. 【咸鱼教程】TextureMerger1.6.6 二:Sprite Sheet的制作和使用

    Sprite Sheet主要用于将零碎的小图合并成一张整图.减少加载图片时http的请求次数. 1 打开TextureMerger,选择Sprite Sheet 2  添加纹理(未创建项目时,会先弹出 ...

  6. Unity3D笔记 愤怒的小鸟<四> 实现Selelction界面

    一直跟着龚老师用js写,VS智能感应用习惯后发现这里用js对初学者比较蛋疼,MONO有提示但是还是无法和VS媲美就目前来看.所以这次还是换成熟悉的VS来开发. 目标:实现关卡页面 跑起来的效果如下: ...

  7. 一个js文件如何加载另外一个js文件

    方法一,在调用文件的顶部加入下例代码: document.write(”<script language=javascript src=’/js/import.js’></scrip ...

  8. srilm使用杂记

    训练n-gram语言模型 ngram-count -text train.txt -order -lm model -kndiscount -interpolate -gt3min -gt4min 计 ...

  9. springMVC去掉静态资源的拦截

    前端控制器的配置 <!-- springmvc的前端控制器 --> <servlet> <servlet-name>springMVC</servlet-na ...

  10. sublime--将vue代码进行高亮显示

    vue的.vue文件sublime是不认识,但是为了让 .vue 文件看上去更加简洁:所以要用到一款不错的插件: 下载:vue-syntax-highlight https://gitee.com/m ...