Easy BFS Java code


  • 1
    L
    public class Solution {
        public char[][] updateBoard(char[][] board, int[] click) {
            int m = board.length, n = board[0].length;
            Queue<int[]> q = new LinkedList<>();
            
            if(board[click[0]][click[1]] == 'M') {
                board[click[0]][click[1]] = 'X';
                return board;
            } else {
                board[click[0]][click[1]] = 'B';
            }
            
            int[] dx = {1, 1, 0, -1, -1, -1,  0, 1};
            int[] dy = {0, 1, 1,  1,  0, -1, -1, -1};
            
            q.offer(click);
            
            while(!q.isEmpty()) {
                int[] cur = q.poll();
                
                int count = 0;
                
                for(int k = 0; k < 8; k++) {
                    int i = cur[0] + dx[k], j = cur[1] + dy[k];
                    if(i < 0 || i >= m || j < 0 || j >= n) continue;
                    if(board[i][j] == 'M') {
                        count++;
                    }
                }
                
                if(count != 0) {
                    board[cur[0]][cur[1]] = (char)('0' + count);
                } else {
                    for(int k = 0; k < 8; k++) {
                        int i = cur[0] + dx[k], j = cur[1] + dy[k];
    
                        if(i < 0 || i >= m || j < 0 || j >= n) continue;
                        if(board[i][j] == 'E') {
                            board[i][j] = 'B';
                            q.offer(new int[] {i, j});
                        }
                    }
                }
            }
            
            return board;
        }
    }
    

Log in to reply
 

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