[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 ...
随机推荐
- 【PHP】 curl 上传文件 流
在运行过程中, 以下两种方式要看你的PHP 版本 'file' =>'@' .$filePath 'file' =>new CURLFile(realpath($filePath)) 本次 ...
- filter对数组和对象的过滤
1,对数组的过滤 let arr = ['1', '2', '3'] let b = arr.filter(val => val === '2') console.log(b) // ['2] ...
- if中的-n -z linux_Shell
==========1 混淆的-n -z================= -n 表示这个变量或者字符串是否不为空.-z 表示这个变量或者字符串为空 上面这两句话中最重要的点是不通的 -n 关注的是 ...
- Unity3D 面试ABC
最先执行的方法是: 1.(激活时的初始化代码)Awake,2.Start.3.Update[FixUpdate.LateUpdate].4.(渲染模块)OnGUI.5.再向后,就是卸载模块(TearD ...
- iOS - 长按图片识别图中二维码
长按图片识别图中二维码: // 长按图片识别二维码 UILongPressGestureRecognizer *QrCodeTap = [[UILongPressGestureRecognizer a ...
- R的any和all
> x<-1:10 > any(x>8) [1] TRUE > all(x>8) [1] FALSE
- POJ-1456 Supermarket(贪心,并查集优化)
Supermarket Time Limit: 2000MS Memory Limit: 65536K Total Submissions: 10725 Accepted: 4688 Descript ...
- TOP100summit:【分享实录-封宇】58到家多端消息整合之路
本篇文章内容来自2016年TOP100summit 58到家架构师封宇的案例分享. 编辑:Cynthia 2017年11月9-12日北京国家会议中心第六届TOP100summit,留言评论有机会获得免 ...
- 2.2RNN
RNN RNN无法回忆起长久的记忆 LSTM (long short Term memory长短期记忆)解决梯度消失或弥散vanishing 和梯度爆炸explosion 0.9*n-->0 ...
- codeforces 355C - Vasya and Robot
因为在允许的情况下,必然是左右手交替进行,这样不会增加多余的无谓的能量. 然后根据不同的分界点,肯定会产生左手或右手重复使用的情况,这是就要加上Qr/Ql * 次数. 一开始的想法,很直接,枚举每个分 ...