Java solution, BFS using Queue


  • 0
    Y
    public class Solution {
        int[][] dirs = new int[][]{{-1, -1}, {-1, 0}, {-1, 1}, {0, -1}, {0, 1}, {1, -1}, {1, 0}, {1, 1}};
        
        public char[][] updateBoard(char[][] board, int[] click) {
    
            int m = board.length;
            int n = board[0].length;
    
            int row = click[0];
            int col = click[1];
            
            if (board[row][col] == 'M') {
                board[row][col] = 'X';
                return board;
            }
            
            if (board[row][col] == 'E') {
                int mines = countmine(board, row, col);
                if (mines > 0) {
                    board[row][col] = (char) ('0' + mines);
                    return board;
                }
                    
                board[row][col] = 'B';
                        
                Queue<Integer> q = new LinkedList<>();
                q.offer(row * n + col);
                while (!q.isEmpty()) {
                    int tmp = q.poll();
                    for (int[] dir : dirs) {
                        int x = tmp / n + dir[0];
                        int y = tmp % n + dir[1];
                        if (x >= 0 && x < m && y >= 0 && y < n && (board[x][y] == 'E')) {
                            mines = countmine(board, x, y);
                            if (mines > 0) {
                                board[x][y] = (char) ('0' + mines);
                            } else {
                                board[x][y] = 'B';
                                q.offer(x * n + y);
                            }
                        }
                    }
                }
            }
            return board;
        }
        
        private int countmine(char[][] board, int row, int col) {
            int res = 0;
            for (int[] dir : dirs) {
                    int x = row + dir[0];
                    int y = col + dir[1];
                    if (x >= 0 && x < board.length && y >= 0 && y < board[0].length && (board[x][y] == 'M' || board[x][y] == 'X'))
                            res++;
            }
            return res;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.