[LeetCode] 529. Minesweeper_ Medium_ tag: BFS
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:
- If a mine ('M') is revealed, then the game is over - change it to 'X'.
- 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.
- 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.
- 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:
- The range of the input matrix's height and width is [1,50].
- The click position will only be an unrevealed square ('M' or 'E'), which also means the input board contains at least one clickable square.
- The input board won't be a stage when game is over (some mines have been revealed).
- 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的更多相关文章
- [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 ...
- [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 ...
- [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 ...
- [LeetCode] 690. Employee Importance_Easy tag: BFS
You are given a data structure of employee information, which includes the employee's unique id, his ...
- [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 ...
- [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 ...
- [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 ...
- [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 ...
- Leetcode之广度优先搜索(BFS)专题-529. 扫雷游戏(Minesweeper)
Leetcode之广度优先搜索(BFS)专题-529. 扫雷游戏(Minesweeper) BFS入门详解:Leetcode之广度优先搜索(BFS)专题-429. N叉树的层序遍历(N-ary Tre ...
随机推荐
- 支持AIRPLAY ,DLNA,MIRACAST的HDMI DONGLE
好吧,今天没节操,帮老婆推广一下淘宝的店. 联我影棒 http://item.taobao.com/item.htm?spm=a230r.1.14.132.jqGLCa&id=36476326 ...
- Android 屏幕适配:最全面的解决方案
转自:https://www.jianshu.com/p/ec5a1a30694b 前言 Android的屏幕适配一直以来都在折磨着我们Android开发者,本文将结合: Google的官方权威适配文 ...
- 题目1003:A+B(按逗号分隔的A+B)
题目链接:http://ac.jobdu.com/problem.php?pid=1003 详解链接:https://github.com/zpfbuaa/JobduInCPlusPlus 参考代码: ...
- shell 中的$0 $1 $* $@ $# $$ $? $() $(())
$0: 脚本本身文件名称 : 命令行第一个参数,$2为第二个,以此类推 $*: 所有参数列表 $@: 所有参数列表 $#: 参数个数 $$: 脚本运行时的PID $?: 脚本退出码 ∗与@的区别 当命 ...
- Memcached存Session数据、访问安全性、使用场景总结(3)
最近做了一个单点登录SSO,登陆后的凭证放到Memcached令牌放到Cookies:但是用户经常掉线,开发环境和测试却没有这个问题,最后从Memcached找到原因. Memcached概念.作用. ...
- H3C系列之三层交换机开启telnet管理的配置
环境介绍>>>>>>>>>>>>>>>>>>>>交换机名牌:H3C交换机类型:三 ...
- vue之创建组建
vue的核心基础就是组件的使用,玩好了组件才能将前面学的基础更好的运用起来.组件的使用更使我们的项目解耦合.更加符合vue的设计思想MVVM. 那接下来就跟我看一下如何在一个Vue实例中使用组件吧! ...
- dos 磁盘操作系统
- HDU-1011 Starship Troopers(树形dp)
Starship Troopers Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others) ...
- hdu5692【dfs序】【线段树】
Snacks Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)Total Sub ...