Recursive Java Solution


  • 0
    R

    Idea is simple: If the clicked tile is not a mine, then we recursively evaluate all adjacent tiles.
    We use a helper function to count adjacent mines. If we find adjacent mines, mark tile with '1' - '8' and stop recursing. Otherwise, we mark the tile as 'B' and continue.

    public class Solution {
        public char[][] updateBoard(char[][] board, int[] click) {
            int row = click[0], col = click[1];
            
            if (board[row][col] != 'M')
                recurseUpdate(row, col, board);
            else
                board[row][col] = 'X';
                
            return board;
        }
        
        public void recurseUpdate(int row, int col, char[][] board) {
            if (row >= board.length || row < 0 || col >= board[0].length || col < 0) return; // out of bounds
    
            if (board[row][col] == 'E') {
                int mines = adjMines(row, col, board); // count adjacent mines
                if (mines > 0)
                    board[row][col] = Character.forDigit(mines, 10);
                else {
                    board[row][col] = 'B';
                    // recurse for adjacents
                    recurseUpdate(row + 1, col, board); // up
                    recurseUpdate(row - 1, col, board); // down
                    recurseUpdate(row, col + 1, board); // right
                    recurseUpdate(row, col - 1, board); // left
                    recurseUpdate(row + 1, col + 1, board); // diagonal up-right
                    recurseUpdate(row - 1, col - 1, board); // diagonal bottom-left
                    recurseUpdate(row - 1, col + 1, board); 
                    recurseUpdate(row + 1, col - 1, board);
                }
            }
        }
        
        public int adjMines(int row, int col, char[][] board) {
            int mines = 0;
            mines += countMines(row + 1, col, board);
            mines += countMines(row - 1, col, board);
            mines += countMines(row, col + 1, board);
            mines += countMines(row, col - 1, board);
            mines += countMines(row + 1, col + 1, board);
            mines += countMines(row - 1, col - 1, board);
            mines += countMines(row - 1, col + 1, board);
            mines += countMines(row + 1, col - 1, board);
            
            return mines;
        }
        
        public int countMines(int row, int col, char[][] board) {
            if (row >= board.length || row < 0 || col >= board[0].length || col < 0) return 0; // out of bounds
            else if (board[row][col] == 'M') return 1;
            return 0;
        }
    }
    

Log in to reply
 

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