Given a Minesweeper board and a click position, reveal cells according to Minesweeper rules: reveal empty cells and expand; stop at numbered cells.
Input: board=[[E,E,E],[E,E,M],[E,E,E]], click=[3,0] → Output: [[B,1,E],[B,1,M],[B,1,E]]
BFS/DFS from click: if the cell is a mine (M), mark as X and return. Otherwise, count adjacent mines. If count > 0, mark as digit and stop. If 0, mark as B and expand to 8 neighbors.
- If board[r][c] == M: mark as X, return.
- Count adjacent mines (8 directions). If count>0: mark as digit char, stop.
- If count==0: mark as B, BFS/DFS to all 8 neighbors that are E.
import java.util.*;
class Solution {
public char[][] updateBoard(char[][] board, int[] click) {
int r = click[0], c = click[1];
if (board[r][c] == 'M') { board[r][c] = 'X'; return board; }
int m = board.length, n = board[0].length;
int[][] dirs = {{-1,-1},{-1,0},{-1,1},{0,-1},{0,1},{1,-1},{1,0},{1,1}};
Queue<int[]> q = new LinkedList<>();
q.offer(click); board[r][c] = 'B';
while (!q.isEmpty()) {
int[] cur = q.poll();
int mines = 0;
List<int[]> neighbors = new ArrayList<>();
for (int[] d : dirs) {
int nr=cur[0]+d[0], nc=cur[1]+d[1];
if (nr>=0&&nr<m&&nc>=0&&nc<n) {
if (board[nr][nc]=='M') mines++;
else if (board[nr][nc]=='E') neighbors.add(new int[]{nr,nc});
}
}
if (mines > 0) board[cur[0]][cur[1]] = (char)('0'+mines);
else for (int[] nb : neighbors) { board[nb[0]][nb[1]]='B'; q.offer(nb); }
}
return board;
}
}
- Time Complexity: O(M*N)
- Space Complexity: O(M*N)