Simple Recursive Solution : JAVA


  • 0
    G
    public class Solution {
        int rows, cols;
        char[][] board;
        
        public char[][] updateBoard(char[][] board, int[] click) {
            rows = board.length;
            cols = board[0].length;
            this.board = board;
            
            reveal(click[0], click[1]);
            return board;
        }
        
        private boolean reveal(int x, int y) {
            if(board[x][y] == 'M') {
                board[x][y] = 'X'; //RULE 1
                return false;
            }
            
             if(board[x][y] == 'E') {
                 List<Cell> coords = getAdjancentCoords(x, y);
                 
                 //Get count for this cell based on adjacent mines
                 int cnt = 0;
                 for(Cell coord : coords) if(board[coord.x][coord.y] == 'M') cnt++;
                 
                 if(cnt > 0) {
                     board[x][y] = (char) (48 + cnt); //RULE 3
                 } else {
                     board[x][y] = 'B';
                     for(Cell coord : coords) {
                        //RULE 2: reveal recursively 
                        if(!reveal(coord.x, coord.y)) return false;
                     }
                 }
             }
            return true; //RULE 4
        }
        
        private List<Cell> getAdjancentCoords(int x, int y) {
            List<Cell> coords = new ArrayList<>();
            
            if(y > 0) coords.add(new Cell(x, y-1)); // LEFT
            if(x > 0 && y > 0) coords.add(new Cell(x-1, y-1)); //TOP LEFT
            
            if(x > 0) coords.add(new Cell(x-1, y)); //TOP
            if(x > 0 && y < cols-1) coords.add(new Cell(x-1, y+1)); //TOP RIGHT
            if(y < cols-1) coords.add(new Cell(x, y+1)); //RIGHT
            
            if(x < rows -1 && y < cols-1) coords.add(new Cell(x+1, y+1)); //BOTTOM RIGHT
            if(x < rows -1) coords.add(new Cell(x+1, y)); //BOTTOM
            if(x < rows -1 && y > 0) coords.add(new Cell(x+1, y-1)); //BOTTOM LEFT
            
            return coords;
        }
        
        public class Cell {
            int x, y;
            public Cell(int x, int y) {
                this.x = x;
                this.y = y;
            }
        }     
    }
    
    

Log in to reply
 

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