[LeetCode] 529. Minesweeper

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[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的主要内容,如果未能解决你的问题,请参考以下文章

leetcode529

Leetcode之广度优先搜索(BFS)专题-529. 扫雷游戏(Minesweeper)

[LeetCode] 529. Minesweeper_ Medium_ tag: BFS

529. Minesweeper

LeetCode 0529. 扫雷游戏

LeetCode 0529. 扫雷游戏