Easy Concise Java DFS Solution (5ms beat %99)


  • 0
    public class Solution {
        
        private void dfs(char[][] board, int r, int c) {
            int h = board.length;
            int w = board[0].length;
            
            int adjacentMineCount = 0;
            for(int i=r-1; i<=r+1; i++)
                for(int j=c-1; j<=c+1; j++)
                    if(i>=0 && i<h && j>=0 && j<w && board[i][j]=='M')
                        adjacentMineCount++;
            
            if(adjacentMineCount > 0) {
                board[r][c] = (char)('0'+adjacentMineCount);
            } else {
                board[r][c] = 'B';
                for(int i=r-1; i<=r+1; i++)
                    for(int j=c-1; j<=c+1; j++)
                        if(i>=0 && i<h && j>=0 && j<w && board[i][j]=='E')
                            helper(board, i, j);
            }
        }
        
        public char[][] updateBoard(char[][] board, int[] click) {
            int r = click[0];
            int c = click[1];
            
            if(board[r][c]=='M') {
                board[r][c] = 'X';
                return board;
            } else {
                dfs(board, r, c);
                return board;
            }
        }
    }

Log in to reply
 

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