529. Minesweeper
Explanation:
To solve this problem, we can use a depth-first search (DFS) approach to reveal squares on the board based on the rules provided. We will start by checking the click position and its neighboring squares to determine the appropriate action for each square. We will update the board accordingly until no more squares can be revealed.
Algorithm:
- If the click position is a mine, change it to 'X' and return the board.
- If the click position is an empty square with no adjacent mines, change it to 'B' and recursively reveal all adjacent unrevealed squares by calling the DFS function.
- If the click position is an empty square with adjacent mines, change it to the number of adjacent mines.
- In the DFS function, for each unrevealed square adjacent to the current square, repeat steps 2 and 3.
Time Complexity:
The time complexity of this algorithm is O(m*n) where m is the number of rows and n is the number of columns in the board.
Space Complexity:
The space complexity of this algorithm is O(m*n) due to the recursive calls in the DFS function.
:
class Solution {
public char[][] updateBoard(char[][] board, int[] click) {
int row = click[0];
int col = click[1];
if (board[row][col] == 'M') {
board[row][col] = 'X';
} else {
dfs(board, row, col);
}
return board;
}
private void dfs(char[][] board, int row, int col) {
if (row < 0 || row >= board.length || col < 0 || col >= board[0].length || board[row][col] != 'E') {
return;
}
int mines = countAdjacentMines(board, row, col);
if (mines == 0) {
board[row][col] = 'B';
int[][] dirs = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}, {-1, -1}, {1, 1}, {-1, 1}, {1, -1}};
for (int[] dir : dirs) {
dfs(board, row + dir[0], col + dir[1]);
}
} else {
board[row][col] = (char) (mines + '0');
}
}
private int countAdjacentMines(char[][] board, int row, int col) {
int count = 0;
int[][] dirs = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}, {-1, -1}, {1, 1}, {-1, 1}, {1, -1}};
for (int[] dir : dirs) {
int newRow = row + dir[0];
int newCol = col + dir[1];
if (newRow >= 0 && newRow < board.length && newCol >= 0 && newCol < board[0].length && board[newRow][newCol] == 'M') {
count++;
}
}
return count;
}
}
Code Editor (Testing phase)
Improve Your Solution
Use the editor below to refine the provided solution. Select a programming language and try the following:
- Add import statement if required.
- Optimize the code for better time or space complexity.
- Add test cases to validate edge cases and common scenarios.
- Handle error conditions or invalid inputs gracefully.
- Experiment with alternative approaches to deepen your understanding.
Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.