Java BFS iterative


  • 0
    C
    public char[][] updateBoard(char[][] board, int[] click) {
            int[][] moves = {{0,-1}, {0,1}, {-1,0}, {1,0}, {1,1}, {-1,1}, {1,-1}, {-1,-1}};
            
            Stack<int[]> stack = new Stack<int[]>();
            stack.push(new int[]{click[0], click[1]});
            
            while(!stack.isEmpty()){
                int[] top = stack.pop();
                
                // game over;
                if(board[top[0]][top[1]] == 'M'){
                    board[top[0]][top[1]] = 'X';
                    return board;
                }
                else if(board[top[0]][top[1]] == 'E'){
                    int adjacentMines = 0;
                    Stack<int[]> adjacentStack = new Stack<int[]>();
                    for(int[] move : moves){
                        int x = top[0] + move[0];
                        int y = top[1] + move[1];
                        
                        if(x<0 || x>= board.length || y<0 || y>= board[0].length){
                            continue;
                        }
                        
                        if(board[x][y] == 'M'){
                            adjacentMines++;
                        }
                        
                        if(board[x][y] == 'E'){
                            adjacentStack.push(new int[]{x,y});
                        }
                    }
                    
                    board[top[0]][top[1]] = adjacentMines == 0 ? 'B' : (char) ('0' + adjacentMines);
                    if(board[top[0]][top[1]] == 'B'){
                        while(!adjacentStack.isEmpty()){
                            stack.push(adjacentStack.pop());
                        }
                    }
                    
                }            
            }
            
            return board;
        }
    

Log in to reply
 

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