Simple Java Recursive Solution


  • 0
    S
    public class Solution {
        boolean flag = false;
        public char[][] updateBoard(char[][] board, int[] click) {
            for(int i = 0; i < click.length - 1 ;i++){
                if(!flag)
                    updateBoardHelper(board,click[i],click[i+1]);
                else
                    break;
            }
            return board;
        }
        
        public void updateBoardHelper(char[][] board, int i, int j){
            if(i < 0 || i >= board.length || j < 0 || j >= board[0].length || (board[i][j] != 'E' && board[i][j] != 'M'))
                return;
            if(board[i][j] == 'M'){
                board[i][j] = 'X';
                flag = true;
                return;
            }
            int count = 0;
            if(i-1 >= 0)
                count = (board[i-1][j] == 'M') ? count + 1 : count;
            if(i+1 < board.length)
                count = (board[i+1][j] == 'M') ? count + 1 : count;
            if(j-1 >= 0)
                count = (board[i][j-1] == 'M') ? count + 1 : count;
            if(j+1 < board[0].length)
                count = (board[i][j+1] == 'M') ? count + 1 : count;
            if(i-1 >= 0 && j-1 >= 0)
                count = (board[i-1][j-1] == 'M') ? count + 1 : count;
            if(i-1 >= 0 && j+1 < board[0].length)
                count = (board[i-1][j+1] == 'M') ? count + 1 : count;
            if(i+1 < board.length && j-1 >= 0)
                count = (board[i+1][j-1] == 'M') ? count + 1 : count;
            if(i+1 < board.length && j+1 < board[0].length)
                count = (board[i+1][j+1] == 'M') ? count + 1 : count;
            board[i][j] = count != 0 ? (char) (count + 48) : 'B';
            if(board[i][j] == 'B'){
                updateBoardHelper(board,i-1,j-1);
                updateBoardHelper(board,i-1,j);
                updateBoardHelper(board,i-1,j+1);
                updateBoardHelper(board,i,j-1);
                updateBoardHelper(board,i,j+1);
                updateBoardHelper(board,i+1,j-1);
                updateBoardHelper(board,i+1,j);
                updateBoardHelper(board,i+1,j+1);    
            }
        }
    }
    

Log in to reply
 

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