Share my easy understand java solution


  • 0
    A
       private static final int[][] dirs = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}, {1, 1}, {-1, -1}, {-1, 1}, {1, -1}};
    
       private int countMine(char[][] board, int i, int j) {
           int total = 0;
           for (int[] dir: dirs) {
               int r = i + dir[0];
               int c = j + dir[1];
               if (r < 0 || c < 0 || r >= board.length || c >= board[0].length) {
                   continue;
               }
               
               if (board[r][c] == 'M') {
                   total++;
               }
           }
           return total;
       }
    
       public char[][] updateBoard(char[][] board, int[] click) {
    	   if (board == null || board.length == 0) {
    		   return board;
    	   }
    
    	   if (click[0] < 0 || click[1] < 0 || click[0] >= board.length || click[1] >= board[0].length) {
        	   return board;
           }
           if (board[click[0]][click[1]] == 'M') {
        	   board[click[0]][click[1]] = 'X';
        	   return board;
           }
           return helper(board, click);
       }
       
       private char[][] helper(char[][] board, int[] click) {
           if (click[0] < 0 || click[1] < 0 || click[0] >= board.length || click[1] >= board[0].length) {
        	   return board;
           }
           
           if (board[click[0]][click[1]] == 'E') {
        	   int count = countMine(board, click[0], click[1]); 
        	   if ( count == 0) {
        		   board[click[0]][click[1]] = 'B';
        		   for (int[] dir : dirs) {
        			   helper(board, new int[]{click[0] + dir[0], click[1] + dir[1]});
        		   }
        	   }    	   
        	   else {
        		   board[click[0]][click[1]] = (char)('0' + count);
        	   }
           }
           return board;
    	   
       }
    
    

Log in to reply
 

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