首页 > 代码库 > [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