Easy Java Solution


  • 0
    U

    Description -
    private static int[][] visited - To keep a track of visited positions. If position x, y is already visited then visited[x][y] = 1 else visited[x][y] = 0

    private static char[][] b - To keep a private static reference to the board. This avoids passing board as a parameter in multiple function calls

    isValid(int x, int y) - returns true if position x, y are within board boundary and false otherwise

    getMineCount(int x, int y) - returns count of total mines around position x, y

    checkForMine(int x, int y) - returns 1 if position x, y has mine and else returns 0

    recur(int x, int y) - returns the count of mines around position x, y and also recursively reveals other positions. It stops recursion when position becomes invalid or a mine is found at the position or an integer is found at the position.

    private static int[][] visited;
    static char[][] b;
    public static char[][] updateBoard(char[][] board, int[] click) {
            b = board;
            visited = new int[board.length][board[0].length];
            int x = click[0], y = click[1];
            if (b[x][y] == 'M') {
                b[x][y] = 'X';
                return board;
            }
            if (b[x][y] == 'E') {
                recur(x, y);
            }
            return board;
        }
    
        private static int recur(int x, int y) {
            if (!isValid(x, y))
                return -1;
            if (visited[x][y] == 1)
                return 0;
            visited[x][y] = 1;
            int count = getMineCount(x, y);
    
            if (count > 0)
                b[x][y] = Character.forDigit(count, 10);
            else {
                b[x][y] = 'B';
                recur(x, y + 1);
                recur(x, y - 1);
                recur(x + 1, y + 1);
                recur(x + 1, y - 1);
                recur(x - 1, y - 1);
                recur(x - 1, y + 1);
                recur(x - 1, y);
                recur(x + 1, y);
            }
            return count;
        }
    
        private static boolean isValid(int x, int y) {
            if (x < 0 || x >= b.length)
                return false;
            if (y < 0 || y >= b[0].length)
                return false;
            return true;
        }
        
        private static int getMineCount(int x, int y) {
            return checkForMine(x, y + 1) + checkForMine(x, y - 1) + checkForMine(x + 1, y + 1) + checkForMine(x + 1, y - 1) + checkForMine(x - 1, y - 1) + checkForMine(x - 1, y + 1) + checkForMine(x - 1, y) + checkForMine(x + 1, y);
        }
    
        private static int checkForMine(int x, int y) {
            if (isValid(x, y)) {
                if (b[x][y] == 'M')
                    return 1;
                return 0;
            }
            return 0;
        }
    

Log in to reply
 

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