标签:索引 point traversal 专题 sem queue 计算 代码 忽略
Leetcode之广度优先搜索(BFS)专题-529. 扫雷游戏(Minesweeper)
BFS入门详解:Leetcode之广度优先搜索(BFS)专题-429. N叉树的层序遍历(N-ary Tree Level Order Traversal)
让我们一起来玩扫雷游戏!
给定一个代表游戏板的二维字符矩阵。 ‘M‘ 代表一个未挖出的地雷,‘E‘ 代表一个未挖出的空方块,‘B‘ 代表没有相邻(上,下,左,右,和所有4个对角线)地雷的已挖出的空白方块,数字(‘1‘ 到 ‘8‘)表示有多少地雷与这块已挖出的方块相邻,‘X‘ 则表示一个已挖出的地雷。
现在给出在所有未挖出的方块中(‘M‘或者‘E‘)的下一个点击位置(行和列索引),根据以下规则,返回相应位置被点击后对应的面板:
示例 1:
输入: [[‘E‘, ‘E‘, ‘E‘, ‘E‘, ‘E‘], [‘E‘, ‘E‘, ‘M‘, ‘E‘, ‘E‘], [‘E‘, ‘E‘, ‘E‘, ‘E‘, ‘E‘], [‘E‘, ‘E‘, ‘E‘, ‘E‘, ‘E‘]] Click : [3,0] 输出: [[‘B‘, ‘1‘, ‘E‘, ‘1‘, ‘B‘], [‘B‘, ‘1‘, ‘M‘, ‘1‘, ‘B‘], [‘B‘, ‘1‘, ‘1‘, ‘1‘, ‘B‘], [‘B‘, ‘B‘, ‘B‘, ‘B‘, ‘B‘]] 解释:
示例 2:
输入: [[‘B‘, ‘1‘, ‘E‘, ‘1‘, ‘B‘], [‘B‘, ‘1‘, ‘M‘, ‘1‘, ‘B‘], [‘B‘, ‘1‘, ‘1‘, ‘1‘, ‘B‘], [‘B‘, ‘B‘, ‘B‘, ‘B‘, ‘B‘]] Click : [1,2] 输出: [[‘B‘, ‘1‘, ‘E‘, ‘1‘, ‘B‘], [‘B‘, ‘1‘, ‘X‘, ‘1‘, ‘B‘], [‘B‘, ‘1‘, ‘1‘, ‘1‘, ‘B‘], [‘B‘, ‘B‘, ‘B‘, ‘B‘, ‘B‘]] 解释:
注意:
这题可以用DFS/BFS写,在BFS专题下,我们尝试用BFS求解这题:
思路如下:
1、从Click点开始
2、BFS
AC代码:
class Solution { public static class POINT { int x, y; POINT(int x, int y) { this.x = x; this.y = y; } } public int getM(char[][] board,int xx,int yy){ int cnt = 0; for (int k = 0; k < 8; k++) { int newx = xx + dirx[k]; int newy = yy + diry[k]; if (newx >= 0 && newx < board.length && newy >= 0 && newy < board[0].length && (board[newx][newy] == ‘M‘ || board[newx][newy] == ‘X‘)) { cnt++; } } return cnt; } int dirx[] = {0, 1, 1, 1, 0, -1, -1, -1}; int diry[] = {1, 1, 0, -1, -1, -1, 0, 1}; int[][] vis ; public char[][] updateBoard(char[][] board, int[] click) { int x = click[0]; int y = click[1]; if (board[x][y] == ‘M‘) { board[x][y] = ‘X‘; return board; } vis = new int[board.length][board[0].length]; Queue<POINT> queue = new LinkedList<>(); vis[x][y] = 1; queue.offer(new POINT(x,y)); while (!queue.isEmpty()) { POINT point = queue.poll(); int xx = point.x; int yy = point.y; int cnt = getM(board,xx,yy); //附近炸弹数量 if (cnt > 0) { board[xx][yy] = (char) (cnt + ‘0‘); } else { board[xx][yy] = ‘B‘; for (int k = 0; k < 8; k++) { int newx = xx + dirx[k]; int newy = yy + diry[k]; if (newx >= 0 && newx < board.length && newy >= 0 && newy < board[0].length && vis[newx][newy]==0) { queue.offer(new POINT(newx,newy)); vis[newx][newy] = 1; } } } } return board; } }
Leetcode之广度优先搜索(BFS)专题-529. 扫雷游戏(Minesweeper)
标签:索引 point traversal 专题 sem queue 计算 代码 忽略
原文地址:https://www.cnblogs.com/qinyuguan/p/11440019.html