Javascript solution using DFS


  • 0
    S
    /**
     * @param {character[][]} board
     * @param {number[]} click
     * @return {character[][]}
     */
    var updateBoard = function(board, click) {
        // edge cases
        if (!board || board.length === 0 ||
            !click || click[0] > board.length ||
            click[1] > board[0].length ||
            click[0] < 0 || click[1] < 0
        ) { return board; }
        
        // hit M and explode
        if (board[click[0]][click[1]] === 'M') {
            board[click[0]][click[1]] = 'X';
            return board;
        }
        
        // hit E
        if (board[click[0]][click[1]] === 'E') {
            helper(board, click[0], click[1]);   
        }
        
        return board;
    };
    
    var helper = function(board, x, y) {
        let xDelta = [-1, -1, -1, 1, 1, 1, 0, 0];
        let yDelta = [1, 0, -1, 1, 0, -1, 1, -1];
    
        let count = 0;
        for (let j = 0; j < 8; j++) {
            if (x + xDelta[j] >= 0 && x + xDelta[j] < board.length &&
                y + yDelta[j] >= 0 && y + yDelta[j] < board[0].length &&
                board[x + xDelta[j]][y + yDelta[j]] === 'M'
            ) { count++; }
        }
        
        if (count > 0) {
            board[x][y] = `${count}`;
        } else {
            board[x][y] = 'B';
            for (let i = 0; i < 8; i++) {
                let newX = x + xDelta[i];
                let newY = y + yDelta[i];
                if (newX >= 0 && newX < board.length &&
                    newY >= 0 && newY < board[0].length &&
                    board[newX][newY] === 'E'
                ) {
                    helper(board, newX, newY);
                }
            }
        }
    };
    

Log in to reply
 

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