[LeetCode] 529. Minesweeper 扫雷
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.
扫雷游戏,经典的搜索问题。
1. 当点击到雷('M')时,标记为'X',结束搜索,游戏结束。
2. 当点击到空方块('E')时,如果周围有雷,就计算雷的个数,标记为这个数字,不在搜索。如果周围没有雷的话, 标记为'B',继续搜索8个挨着的方块。
解法1:DFS
解法2: BFS
Java: DFS
public class Solution {
public char[][] updateBoard(char[][] board, int[] click) {
int m = board.length, n = board[0].length;
int row = click[0], col = click[1]; if (board[row][col] == 'M') { // Mine
board[row][col] = 'X';
}
else { // Empty
// Get number of mines first.
int count = 0;
for (int i = -1; i < 2; i++) {
for (int j = -1; j < 2; j++) {
if (i == 0 && j == 0) continue;
int r = row + i, c = col + j;
if (r < 0 || r >= m || c < 0 || c < 0 || c >= n) continue;
if (board[r][c] == 'M' || board[r][c] == 'X') count++;
}
} if (count > 0) { // If it is not a 'B', stop further DFS.
board[row][col] = (char)(count + '0');
}
else { // Continue DFS to adjacent cells.
board[row][col] = 'B';
for (int i = -1; i < 2; i++) {
for (int j = -1; j < 2; j++) {
if (i == 0 && j == 0) continue;
int r = row + i, c = col + j;
if (r < 0 || r >= m || c < 0 || c < 0 || c >= n) continue;
if (board[r][c] == 'E') updateBoard(board, new int[] {r, c});
}
}
}
} return board;
}
}
Java: BFS
public class Solution {
public char[][] updateBoard(char[][] board, int[] click) {
int m = board.length, n = board[0].length;
Queue<int[]> queue = new LinkedList<>();
queue.add(click); while (!queue.isEmpty()) {
int[] cell = queue.poll();
int row = cell[0], col = cell[1]; if (board[row][col] == 'M') { // Mine
board[row][col] = 'X';
}
else { // Empty
// Get number of mines first.
int count = 0;
for (int i = -1; i < 2; i++) {
for (int j = -1; j < 2; j++) {
if (i == 0 && j == 0) continue;
int r = row + i, c = col + j;
if (r < 0 || r >= m || c < 0 || c < 0 || c >= n) continue;
if (board[r][c] == 'M' || board[r][c] == 'X') count++;
}
} if (count > 0) { // If it is not a 'B', stop further BFS.
board[row][col] = (char)(count + '0');
}
else { // Continue BFS to adjacent cells.
board[row][col] = 'B';
for (int i = -1; i < 2; i++) {
for (int j = -1; j < 2; j++) {
if (i == 0 && j == 0) continue;
int r = row + i, c = col + j;
if (r < 0 || r >= m || c < 0 || c < 0 || c >= n) continue;
if (board[r][c] == 'E') {
queue.add(new int[] {r, c});
board[r][c] = 'B'; // Avoid to be added again.
}
}
}
}
}
} return board;
}
}
Python:
class Solution(object):
def updateBoard(self, board, click):
"""
:type board: List[List[str]]
:type click: List[int]
:rtype: List[List[str]]
"""
q = collections.deque([click])
while q:
row, col = q.popleft()
if board[row][col] == 'M':
board[row][col] = 'X'
else:
count = 0
for i in xrange(-1, 2):
for j in xrange(-1, 2):
if i == 0 and j == 0:
continue
r, c = row + i, col + j
if not (0 <= r < len(board)) or not (0 <= c < len(board[r])):
continue
if board[r][c] == 'M' or board[r][c] == 'X':
count += 1 if count:
board[row][col] = chr(count + ord('0'))
else:
board[row][col] = 'B'
for i in xrange(-1, 2):
for j in xrange(-1, 2):
if i == 0 and j == 0:
continue
r, c = row + i, col + j
if not (0 <= r < len(board)) or not (0 <= c < len(board[r])):
continue
if board[r][c] == 'E':
q.append((r, c))
board[r][c] = ' ' return board
Python:
# Time: O(m * n)
# Space: O(m * n)
class Solution2(object):
def updateBoard(self, board, click):
"""
:type board: List[List[str]]
:type click: List[int]
:rtype: List[List[str]]
"""
row, col = click[0], click[1]
if board[row][col] == 'M':
board[row][col] = 'X'
else:
count = 0
for i in xrange(-1, 2):
for j in xrange(-1, 2):
if i == 0 and j == 0:
continue
r, c = row + i, col + j
if not (0 <= r < len(board)) or not (0 <= c < len(board[r])):
continue
if board[r][c] == 'M' or board[r][c] == 'X':
count += 1 if count:
board[row][col] = chr(count + ord('0'))
else:
board[row][col] = 'B'
for i in xrange(-1, 2):
for j in xrange(-1, 2):
if i == 0 and j == 0:
continue
r, c = row + i, col + j
if not (0 <= r < len(board)) or not (0 <= c < len(board[r])):
continue
if board[r][c] == 'E':
self.updateBoard(board, (r, c)) return board
C++:
// Time: O(m * n)
// Space: O(m + n) class Solution {
public:
vector<vector<char>> updateBoard(vector<vector<char>>& board, vector<int>& click) {
queue<vector<int>> q;
q.emplace(click);
while (!q.empty()) {
int row = q.front()[0], col = q.front()[1];
q.pop();
if (board[row][col] == 'M') {
board[row][col] = 'X';
} else {
int count = 0;
for (int i = -1; i < 2; ++i) {
for (int j = -1; j < 2; ++j) {
if (i == 0 && j == 0) {
continue;
}
int r = row + i, c = col + j;
if (r < 0 || r >= board.size() || c < 0 || c < 0 || c >= board[r].size()) {
continue;
}
if (board[r][c] == 'M' || board[r][c] == 'X') {
++count;
}
}
} if (count > 0) {
board[row][col] = count + '0';
} else {
board[row][col] = 'B';
for (int i = -1; i < 2; ++i) {
for (int j = -1; j < 2; ++j) {
if (i == 0 && j == 0) {
continue;
}
int r = row + i, c = col + j;
if (r < 0 || r >= board.size() || c < 0 || c < 0 || c >= board[r].size()) {
continue;
}
if (board[r][c] == 'E') {
vector<int> next_click = {r, c};
q.emplace(next_click);
board[r][c] = 'B';
}
}
}
}
}
} return board;
}
};
C++:
// Time: O(m * n)
// Space: O(m * n)
class Solution2 {
public:
vector<vector<char>> updateBoard(vector<vector<char>>& board, vector<int>& click) {
int row = click[0], col = click[1];
if (board[row][col] == 'M') {
board[row][col] = 'X';
} else {
int count = 0;
for (int i = -1; i < 2; ++i) {
for (int j = -1; j < 2; ++j) {
if (i == 0 && j == 0) {
continue;
}
int r = row + i, c = col + j;
if (r < 0 || r >= board.size() || c < 0 || c < 0 || c >= board[r].size()) {
continue;
}
if (board[r][c] == 'M' || board[r][c] == 'X') {
++count;
}
}
} if (count > 0) {
board[row][col] = count + '0';
} else {
board[row][col] = 'B';
for (int i = -1; i < 2; ++i) {
for (int j = -1; j < 2; ++j) {
if (i == 0 && j == 0) {
continue;
}
int r = row + i, c = col + j;
if (r < 0 || r >= board.size() || c < 0 || c < 0 || c >= board[r].size()) {
continue;
}
if (board[r][c] == 'E') {
vector<int> next_click = {r, c};
updateBoard(board, next_click);
}
}
}
}
} return board;
}
};
All LeetCode Questions List 题目汇总
[LeetCode] 529. Minesweeper 扫雷的更多相关文章
- LN : leetcode 529 Minesweeper
lc 529 Minesweeper 529 Minesweeper Let's play the minesweeper game! You are given a 2D char matrix r ...
- LeetCode 529. Minesweeper
原题链接在这里:https://leetcode.com/problems/minesweeper/description/ 题目: Let's play the minesweeper game ( ...
- 529 Minesweeper 扫雷游戏
详见:https://leetcode.com/problems/minesweeper/description/ C++: class Solution { public: vector<ve ...
- 529. Minesweeper扫雷游戏
[抄题]: Let's play the minesweeper game (Wikipedia, online game)! You are given a 2D char matrix repre ...
- [LeetCode] Minesweeper 扫雷游戏
Let's play the minesweeper game (Wikipedia, online game)! You are given a 2D char matrix representin ...
- Week 5 - 529.Minesweeper
529.Minesweeper Let's play the minesweeper game (Wikipedia, online game)! You are given a 2D char ma ...
- leetcode笔记(七)529. Minesweeper
题目描述 Let's play the minesweeper game (Wikipedia, online game)! You are given a 2D char matrix repres ...
- Java实现 LeetCode 529 扫雷游戏(DFS)
529. 扫雷游戏 让我们一起来玩扫雷游戏! 给定一个代表游戏板的二维字符矩阵. 'M' 代表一个未挖出的地雷,'E' 代表一个未挖出的空方块,'B' 代表没有相邻(上,下,左,右,和所有4个对角线) ...
- 【LeetCode】529. Minesweeper 解题报告(Python & C++)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 DFS 日期 题目地址:https://leetco ...
随机推荐
- SQL模糊查询的四种匹配模式
执行数据库查询时,有完整查询和模糊查询之分,一般模糊语句如下: SELECT 字段 FROM 表 WHERE 某字段 Like 条件 一.四种匹配模式 关于条件,SQL提供了四种匹配模式: 1.% 表 ...
- 用IntelliJ IDEA学习Spring--创建一个简单的项目
这段时间想学习一下Spring,其实之前学过Spring,只是有些忘记了.而且之前学的时候是适用eclipse学习的,现在好像对IntelliJ这个工具使用挺多的,现在就学习一下这个工具的用法,顺便复 ...
- 微信小程序之 ECMAScript
在大部分开发者看来,ECMAScript和JavaScript表达的是同一种含义,但是严格的说,两者的意义是不同的.ECMAScript是一种由Ecma国际通过ECMA-262标准化的脚本程序设计语言 ...
- 51nod1712 区间求和
http://www.51nod.com/Challenge/Problem.html#problemId=1712 先考虑题面中的简化问题. 对于\(i\in [1,n]\),\(a_i\)的贡献为 ...
- 10. vue-router命名路由
命名路由的配置规则 为了更加方便的表示路由的路径,可以给路由规则起一个别名, 即为"命名路由". const router = new VueRouter ({ routes: [ ...
- 在linux中使用Sqlplus命令登录MySQL,查看表并设置行数和宽度,使其正常显示
在linux中使用sqlplus命令进入MySQL,设置行数和行宽 1) 查看目前的pagesize,默认是14: 1. show pagesize; 2. set pa ...
- Pycharm中打开Terminal方式
点击剪头的图标就可以在左侧出现Terminal
- navicat 远程连接服务器1130,1045问题报错处理
本人踩坑多次,一开始网上搜罗,解决办法大同小异,摸索了很久才全部解决完成,小小bug真磨人啊 首先,根据我的踩坑记录,navicat 1045和navicat 1130貌似属于同一种解决方案,都是修改 ...
- gin+redis
var RedisDefaultPool *redis.Pool func newPool(addr string) *redis.Pool { return &redis.Pool{ Max ...
- PDB文件会影响性能吗?
有人问了这样的问题:"我工作的公司正极力反对用生成的调试信息构建发布模式二进制文件,这也是我注册该类的原因之一.他们担心演示会受到影响.我的问题是,在发布模式下生成符号的最佳命令行参数是什么 ...