首页 > 代码库 > [LeetCode] 529. Minesweeper
[LeetCode] 529. Minesweeper
https://leetcode.com/problems/minesweeper/
public class Solution { public char[][] updateBoard(char[][] board, int[] click) { if (board == null || board.length == 0) { return board; } if (board[click[0]][click[1]] == ‘M‘) { board[click[0]][click[1]] = ‘X‘; return board; } int[][] diff = {{1, 0}, {-1, 0}, {1, 1}, {-1, 1}, {1, -1}, {-1, -1}, {0, 1}, {0, -1}}; Queue<Integer> queue = new LinkedList<>(); queue.offer(click[0] * board[0].length + click[1]); while (!queue.isEmpty()) { int index = queue.poll(); int i = index / board[0].length; int j = index - i * board[0].length; if (board[i][j] != ‘E‘) { // Without this, Time limit exceeded continue; } int mine = 0; Queue<Integer> neighbors = new LinkedList<>(); for (int[] cur: diff) { int x = i + cur[0]; int y = j + cur[1]; if (x >= 0 && x < board.length && y >= 0 && y < board[0].length) { if (board[x][y] == ‘M‘ || board[x][y] == ‘X‘) { mine++; } if (mine == 0 && board[x][y] == ‘E‘) { neighbors.offer(x * board[0].length + y); } } } if (mine == 0) { board[i][j] = ‘B‘; while (!neighbors.isEmpty()) { queue.offer(neighbors.poll()); } } else { board[i][j] = (char)(mine + ‘0‘); } } return board; } }
[LeetCode] 529. Minesweeper
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。