Java BFS Solution


  • 0
    R
    
    public class Solution {
        public char[][] updateBoard(char[][] board, int[] click) {
            int x = click[0];
            int y = click[1];
            if(board[x][y] == 'M'){
                board[x][y] = 'X';
                return board;
            }
            Stack<int[]> neighbourStack = new Stack<int[]>();
            neighbourStack.push(click);
            
            while(!neighbourStack.empty()){
                int[] currClick = neighbourStack.pop();
                boolean isOver = true;
                int clickCt = checkNeighbour(board, currClick[0], currClick[1], neighbourStack, isOver);
                if(neighbourStack.empty()&&isOver)
                    break;
            }
            return board;
        }
        
        private int checkNeighbour(char[][] board, int x, int y, Stack<int[]> neighbourStack, boolean isOver){
            int count = 0;
            int left = (y==0?0:y-1);
            int right = (y==board[0].length-1?board[0].length-1:y+1);
            int up = (x==0?0:x-1);
            int down = (x==board.length-1?board.length-1:x+1);
            for(int i=up; i<=down; i++){
                for(int j=left; j<=right; j++){
                    
                    if(i==x && j== y){
                        continue;
                    }else{
                        if(board[i][j]=='M'){
                           count++; 
                        }
                        
                    }
                    
                }
            }
            
            if(count > 0){
                board[x][y] = (char)(count+'0');
            }else{
                board[x][y] = 'B';
                for(int i=up; i<=down; i++){
                  for(int j=left; j<=right; j++){
                    
                    if(i==x && j== y){
                        continue;
                    }else{
                        
                        if(board[i][j]=='E'){
                            int[] ss = {i, j};
                            isOver = false;
                            neighbourStack.push(ss);
                            board[i][j] = 'B';
                        }
                    }
                    
                  }
               }
                
            }
            return count;
        }
    }
    
    

Log in to reply
 

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