让我们一起来玩扫雷游戏!
给定一个代表游戏板的二维字符矩阵。 ‘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‘]]
解释:
注意:
BFS,不能一直深搜,因为当前位置如果要显示数字(即周围有几个雷),那么不能对它的四周进行深搜。
因此先count当前四周雷数,如果没有雷才能继续递归搜索
1 public class Solution { 2 int[][] dirs = {{1, 0}, {1, 1}, {1, -1}, {-1, 0}, {-1, 1}, {-1, -1}, {0, 1}, {0, -1}}; 3 public char[][] updateBoard(char[][] board, int[] click) { 4 if (board == null || board.length == 0) { 5 return board; 6 } 7 int i = click[0]; 8 int j = click[1]; 9 if (board[i][j] == ‘M‘) { 10 board[i][j] = ‘X‘; 11 return board; 12 } 13 update(board, i, j); 14 return board; 15 } 16 private void update(char[][] board, int i, int j) { 17 if (board[i][j] != ‘E‘) { 18 return; 19 } 20 int cnt = 0; 21 for (int[] dir : dirs) { 22 int row = dir[0] + i; 23 int col = dir[1] + j; 24 if (row >= 0 && row < board.length && col >= 0 && col < board[0].length && board[row][col] == ‘M‘) { 25 cnt++; 26 } 27 } 28 board[i][j] = ‘*‘; 29 if (cnt == 0) { 30 board[i][j] = ‘B‘; 31 for (int[] dir : dirs) { 32 int row = dir[0] + i; 33 int col = dir[1] + j; 34 if (row >= 0 && row < board.length && col >= 0 && col < board[0].length) { 35 update(board, row, col); 36 } 37 } 38 } else { 39 board[i][j] = (char) (cnt + ‘0‘); 40 } 41 } 42 }
原文:https://www.cnblogs.com/kexinxin/p/10372541.html