Approach
Depth-first search
For Minesweeper, the implementation follows one branch at a time, making it suitable for components, trees, backtracking, or dependency exploration.
- Define the state carried into one recursive or stack frame.
- Mark or choose the current state before exploring children.
- Combine child results or undo the choice when the branch finishes.
Code notes
- 47 lines of C++ from the credited upstream file 529.cpp.
- The implementation visibly relies on sequence storage.
- 2 loop blocks detected, together with recursive traversal.
Complexity
Count unique states for graph traversal; for backtracking, count the branching factor and maximum depth.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public:3 vector<vector<char>> updateBoard(vector<vector<char>>& board,4 vector<int>& click) {5 const int i = click[0];6 const int j = click[1];7 if (board[i][j] == 'M') {8 board[i][j] = 'X';9 return board;10 }11 12 dfs(board, i, j);13 return board;14 }15 16 private:17 static constexpr int kDirs[8][2] = {{-1, -1}, {-1, 0}, {-1, 1}, {0, -1},18 {0, 1}, {1, -1}, {1, 0}, {1, 1}};19 20 void dfs(vector<vector<char>>& board, int i, int j) {21 if (i < 0 || i == board.size() || j < 0 || j == board[0].size())22 return;23 if (board[i][j] != 'E')24 return;25 26 const int minesCount = getMinesCount(board, i, j);27 board[i][j] = minesCount == 0 ? 'B' : '0' + minesCount;28 29 if (minesCount == 0)30 for (const auto& [dx, dy] : kDirs)31 dfs(board, i + dx, j + dy);32 }33 34 int getMinesCount(const vector<vector<char>>& board, int i, int j) {35 int minesCount = 0;36 for (const auto& [dx, dy] : kDirs) {37 const int x = i + dx;38 const int y = j + dy;39 if (x < 0 || x == board.size() || y < 0 || y == board[0].size())40 continue;41 if (board[x][y] == 'M')42 ++minesCount;43 }44 return minesCount;45 }46};47